我们有一个MVC3控制器,其中有一些'常见'工作,我们将其放入控制器构造函数中。一些常见的工作是通过一个可以通过Unity动态解析(用于IoC /依赖注入)的失败耦合类(例如ourService
)完成的。 ourService
在Controller的构造函数中为空(即未解析),但在正常的Controller方法中正确解析。下面这个简单的演示代码显示问题:Unity不解决MVC3控制器构造函数中的依赖关系
public class Testing123Controller : BaseController
{
[Dependency]
public IOurService ourService { get; set; }
public Testing123Controller()
{
ourService.SomeWork(1); // ourService=null here !!
...
}
public ActionResult Index()
{
ourService.SomeWork(1); // resolved properly here here !!
...
}
...
}
问题:
- 为什么会出现在Unity解析行为有何不同?我会期待一致的行为。
- 我该如何解决这个问题,即使在控制器的构造器中,Unity也解决了这个问题?
的方式,我们已经建立统一2.0:
的Global.asax
Application_Start()
{
...
Container = new UnityContainer();
UnityBootstrapper.ConfigureContainer(Container);
DependencyResolver.SetResolver(new UnityDependencyResolver(Container));
...
}
public static void ConfigureContainer(UnityContainer container)
{
...
container.RegisterType<IOurService, OurService>();
...
}
IOurService.cs
public interface IOurService
{
bool SomeWork(int anInt);
}
OurService.cs
public class OurService: IOurService
{
public bool SomeWork(int anInt)
{
return ++anInt; //Whew! Time for a break ...
}
}
好阅读这里:http://www.fascinatedwithsoftware.com/blog/post/2012/02/01/Prefer-Constructor-Injection-Over-Property-Injection.aspx这里有一个很好的解释:http:// stackoverflow.com/questions/11125883/property-dependency-injection-used-in-constructor-using-unity – timothyclifford