我們有一個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