[英]How to register type in the IoC container from an “Area” in ASP.NET MVC 5 app?
您可以創建一個繼承自UnityContainerExtension
的單獨的類,並將其放置在您的區域中,如下所示:
public class MyAreaContainerExtension : UnityContainerExtension
{
protected override void Initialize()
{
Container.RegisterType<IDoesSomething, DoesSomething>();
}
}
然后在您的創業公司,
container.AddNewExtension<MyAreaContainerExtension>();
或者,如果您的擴展具有傳遞給它的構造函數參數(例如其需要的配置數據或應使用的實例),則可以創建擴展的實例,然后執行
container.AddExtension(theExtensionInstanceICreated);
這是一個很好的做法,因為它使您可以使組件注冊更接近要注冊的類,而不是擁有一個包含數十個甚至一百個甚至更多注冊的巨大文件。
這種方法的另一個好處是,隨着組件注冊變得越來越復雜,您可以為這些擴展編寫單元測試,以將擴展添加到容器中,然后從容器中解析對象。
您可能必須注冊其他組件才能使用此擴展程序中注冊的類型,但是您不想在擴展程序中重復這些注冊。 在這種情況下,您可以通過指定必須已經注冊的類型來使其明確,如下所示:
public class MyAreaContainerExtension : UnityContainerExtension
{
protected override void Initialize()
{
AssertRequiredRegistrations();
Container.RegisterType<IDoesSomething, DoesSomething>();
}
private void AssertRequiredRegistrations()
{
AssertRequiredRegistration(typeof(ISomeOtherType));
}
private void AssertRequiredRegistration(Type type)
{
if(!Container.IsRegistered(type))
throw new Exception($"Type {type.FullName} must be registered with the container.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.