我的Unity运行对我的ASP.NET Web API项目中的所有控制器都非常有用 - 只需使用NuGet框中的默认设置.我还设法将其连接到MVC过滤器属性 - 但似乎无法对ASP.NET Web API过滤器属性执行相同操作.
如何扩展此默认实现以将依赖项注入ActionFilterAttribute,例如......
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
[Dependency]
public IMyService myService { get; set; }
public BasicAuthenticationAttribute()
{
}
}
Run Code Online (Sandbox Code Playgroud)
此过滤器使用属性应用于控制器:
[BasicAuthentication]
Run Code Online (Sandbox Code Playgroud)
我很确定我需要连接Unity容器以便它处理属性类的创建,但需要一些关于从哪里开始的线索,因为它不使用与MVC过滤器相同的可扩展性点.
我只想添加,我尝试过的其他内容包括服务位置而不是依赖注入,但是你得到的DependencyResolver与你配置的不一样.
// null
var service = actionContext.Request.GetDependencyScope().GetService(typeof(IMyService));
Run Code Online (Sandbox Code Playgroud)
要么
// null
var service = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IApiUserService));
Run Code Online (Sandbox Code Playgroud) 在使用基于构造函数的DI之后,我正在尝试使用Unity IoC.问题是试图让集成测试工作.
http://patrick.lioi.net/2013/06/20/streamlined-integration-tests/
"运行集成测试应尽可能多地运用真实系统"
上面的Patrick描述了在MVC单元测试项目中设置IoC ..但我仍然坚持如何实现
public class HomeController : Controller
{
readonly IWinterDb db;
// Unity knows that if IWinterDb interface is asked for, it will inject in a new WinterDb()
public HomeController(IWinterDb db)
{
this.db = db;
}
public ActionResult Index()
{
var stories = db.Query<Story>()
.OrderByDescending(s => s.Rating)
.Include(s => s.StoryType);
return View(stories);
}
Run Code Online (Sandbox Code Playgroud)
单元测试很好,传入假的:
[TestMethod]
public void Index_GivenFake_ShouldReturn100Stories()
{
var db = new FakeWinterDb();
db.AddSet(TestData.Stories);
var controller = new HomeController(db);
var result = controller.Index() as …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc integration-testing inversion-of-control unity-container
我正在使用ASP.NET MVC 4应用程序.
家庭控制器的构造函数参数化为2参数(Iservice1 service1,Iservice2 service2)并非所有代码路径都使用任何Service(service1,service2),只在某些代码路径中我需要service1 instance/object或service2 instance/object.
我不想使用container.Resolve < <Lazy<IService1>>();
从这个链接(http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx)我明白unity.mvc 4使用unity 3,它具有Lazy loading支持,但是如何在ASP.NET MVC 4中执行此操作.
asp.net-mvc lazy-loading inversion-of-control unity-container deferred-loading
跟进ASP.New MVC 4 Web Api的授权过滤器依赖注入。有没有一种方法可以对所有控制器类上全局设置的过滤器使用依赖项注入:
config.Filters.Add(new WebApplicationApiAuthorizeAttribute());
Run Code Online (Sandbox Code Playgroud)
看起来该GetFilters方法ActionDescriptorFilterProvider仅适用于方法级过滤器。
public class UnityWebApiFilterAttributeFilterProvider : ActionDescriptorFilterProvider,
System.Web.Http.Filters.IFilterProvider
{
private readonly IUnityContainer _container;
public UnityWebApiFilterAttributeFilterProvider(IUnityContainer container)
{
_container = container;
}
public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration,
HttpActionDescriptor actionDescriptor)
{
var filters = base.GetFilters(configuration, actionDescriptor);
this.BuildUpAttributes(filters);
return filters;
}
private void BuildUpAttributes(IEnumerable filterInfo)
{
foreach (FilterInfo filter in filterInfo)
{
object o = _container.BuildUp(filter.GetType(), filter);
}
}
}
Run Code Online (Sandbox Code Playgroud) asp.net-mvc dependency-injection unity-container asp.net-web-api
我创建了一个适用于依赖性反转原理的类,并使用了依赖注入模式,如下所示:
public interface ITypeOfPrinter
{
string Printing();
}
public class Print
{
private readonly ITypeOfPrinter _typeOfPrinter;
public Print(ITypeOfPrinter typeOfPrinter)
{
_typeOfPrinter = typeOfPrinter;
}
public string print()
{
return _typeOfPrinter.Printing();
}
}
public class BlackAndWhitePrinter : ITypeOfPrinter
{
public string Printing()
{
NumberOfPrints++;
return string.Format("it is Black and white printing {0}", NumberOfPrints);
}
public int NumberOfPrints { get; set; }
}
public class ColorfullPrinter : ITypeOfPrinter
{
public string Printing()
{
NumberOfPrints++;
return string.Format("it is colorfull printing {0}", NumberOfPrints);
} …Run Code Online (Sandbox Code Playgroud) c# unit-testing design-patterns inversion-of-control unity-container
我正在开发一个Web API项目.我正在调用一个负责数据库交互的存储库.存储库与第三方数据源交互.
我想在存储库层实现依赖注入(DI)以注入第三方数据源的依赖关系,但是如何实现这一点,因为该第三方DLL中没有接口?
我使用Unity框架.
第三方DLL只包含一个类:
using System;
using System.Collections.Generic;
namespace MoviesLibrary
{
public class MovieDataSource
{
public MovieDataSource();
public int Create(MovieData movie);
public List<MovieData> GetAllData();
public MovieData GetDataById(int id);
public void Update(MovieData movie);
}
}
Run Code Online (Sandbox Code Playgroud) c# dependency-injection repository unity-container asp.net-web-api
我试图让Unity与我的控制台应用程序一起工作,但是我尝试依赖注入的所有属性仍然设置为null.
这是我的代码:
Program.cs中
namespace .Presentation.Console
{
class Program
{
static void Main(string[] args)
{
var mainThread = new MainThread();
}
}
}
Run Code Online (Sandbox Code Playgroud)
MainThread.cs
namespace xxxx.Presentation.Console
{
public class MainThread
{
public IUnitOfWork UnitOfWork { get; set; }
public IMapper Mapper { get; set; }
public MainThread()
{
Mapper.RegisterMappings();
}
}
}
Run Code Online (Sandbox Code Playgroud)
App.config中
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IDataAccess" type="UnityFramework.IDataAccess, UnityFramework" />
<namespace name="UnityFramework" />
<assembly …Run Code Online (Sandbox Code Playgroud) 我已经看了几个关于如何为MVC 5项目实现统一的教程和stackoverflow问题,但我似乎无法通过这个错误:
无法构造String类型.您必须配置容器以提供此值.
我安装了NuGet包Unity.Mvc5,并在unity配置中注册了我的类型.我还在unityconfig文件中调用了register components方法.
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IStateService, StateService>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
UnityConfig.RegisterComponents();
}
public class StateController : Controller
{
private readonly IStateService stateService;
public StateController(IStateService stateService)
{
this.stateService = stateService;
}
// GET: /State/
public ActionResult Index() …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc entity-framework unity-container asp.net-mvc-5
以下代码适用于版本3.5.1404,但不再适用于版本5.0.1.通过NuGet获得最新参考:
在web.config我有:
using Microsoft.Practices.Unity.Configuration;
using Unity;
namespace ACME.Core
{
public static class UnityCommon
{
static IUnityContainer _container;
/// <summary>
/// Returns the Common Unity Container from memory, reloads if not loaded first
/// </summary>
/// <param name="forceRefresh">Forces the container to be reloaded in memory</param>
/// <returns>IUnityContainer</returns>
public static IUnityContainer GetContainer(bool forceRefresh = false)
{
if (_container == null || forceRefresh)
{
_container = new UnityContainer();
_container.LoadConfiguration("Default"));
}
return _container;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这引用了web.config中的XML映射,例如:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<assembly name="ACME.Core" />
<namespace name="ACME.Core.DTO" …Run Code Online (Sandbox Code Playgroud) 我支持在您的应用程序上使用依赖注入,尽管有些人认为它会给代码增加不必要的复杂性.在过去的几天里,我想知道,在某些情况下,使用DI时可能会有一些浪费.
让我用代码示例解释一下:
使用DI
public class Class
{
private Service1 service1;
private Service2 service2;
public MyClass (Service1 service1, Service2 service2)
{
this.service1 = service1;
this.service2 = service2;
}
private int SampleMethod()
{
Console.WriteLine("doing something with service 1");
service1.DoSomething();
return 0;
}
private int SampleMethod2()
{
Console.WriteLine("doing something with service 2");
service2.DoSomethingElse();
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我很少调用SampleMethod2并且每次需要一个Class实例时我会注入它会怎么样?那不是在浪费资源吗?
我几天前得到了这个问题,我正试图找出答案.是否更容易不使用DI并让每个方法在使用时创建他们需要的实例以避免这种"浪费"?
由于DI提供的解耦,这是否是合理的"浪费"?
.net c# dependency-injection inversion-of-control unity-container
unity-container ×10
c# ×7
asp.net-mvc ×4
.net ×2
console ×1
lazy-loading ×1
repository ×1
unit-testing ×1