[英]ServiceStack IoC/DI: Registering classes in the Container - how to register all that implements a specific interface
[英]How to register all classes that inherits from a base class in Unity.Mvc IoC container?
我有一個使用ASP.NET MVC 5框架頂部的c#編寫的應用程序。
我有以下屬性用於裝飾控制器
namespace Plugin1.Helpers
{
public class PermissionAttribute : MainApp.Helpers.BasePermissionClass
{
public PermissionAttribute()
{
}
public PermissionAttribute(string key)
: base(key, "MVC")
{
}
public PermissionAttribute(string[] keys)
: base(keys, "MVC")
{
}
}
}
以下是如何使用Permission
屬性來裝飾控制器
namespace Plugin1.Controllers
{
[Plugin1.Helpers.Permission(Keys = "some key")]
public class HomeController : Controller
{
// ....
}
}
不幸的是,每次我嘗試從IoC
容器中解析控制器時,我都會收到以下錯誤。
PermissionAttribute類型具有多個長度為1的構造函數。無法消除歧義。
但是,當我為每個PermissionAttribute
類手動添加以下行時,一切都很完美
container.RegisterType<Plugin1.Helpers.PermissionAttribute>(new InjectionConstructor());
container.RegisterType<PluginXYZ.Helpers.PermissionAttribute>(new InjectionConstructor());
但是,我有一個可插入的基本應用程序,每個插件都有一個不同的PermissionAttribute
類。 我沒有讓每個插件手動將自己的PermissionAttribute
類注冊到容器中,而是嘗試使用反射來查找從MainApp.Helpers.BasePermissionClass
繼承的任何類,並在首次啟動應用程序時簡單地注冊它。
在我的MainApp
項目中,我首先搜索任何類型的MainProject.Helpers.BasePermissionClass
子類,然后通過提供new InjectionConstructor()
來注冊它,它應該告訴Unity使用無參數構造函數。
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(x => x.IsClass && !x.IsInterface && !x.IsAbstract && x.IsSubclassOf(typeof(BasePermissionClass))).ToList();
foreach(Type type in types)
{
container.RegisterType(typeof(BasePermissionClass), type, type.FullName, new InjectionConstructor());
}
我通過手動評估已注冊的對象來驗證是否找到了類型並將其注冊到容器中。
我也試着注冊這樣的類型
foreach(Type type in types)
{
container.RegisterType(type.GetType(), type, type.FullName, new InjectionConstructor());
}
但這是拋出以下異常
Plugin1.Helpers.PermissionAttribute類型不能分配給System.RuntimeType類型的變量。 參數名稱:typeFrom
如何使用反射來正確注冊從BasePermissionClass
繼承的任何類
我怎樣才能正確地將每個類注冊到它的類型而不是基類型。
你為什么看到這個錯誤?
Plugin1.Helpers.PermissionAttribute類型不能分配給System.RuntimeType類型的變量。 參數名稱:typeFrom
那是因為.GetType()
方法返回System.RuntimeType
而不是實現的類型。
此外,您不需要獲取類型的類型。 您的type
變量屬於Type
。
相反,嘗試注冊你的課程
var objs = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(x => x.IsClass && !x.IsInterface && !x.IsAbstract && x.IsSubclassOf(typeof(BasePermissionClass))).ToList();
foreach(Type obj in objs)
{
container.RegisterType(obj, new InjectionConstructor());
}
由於您只注冊了實現,因此無需使用密鑰注冊對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.