簡體   English   中英

將所有用 Attribute 注釋的類解析為 IEnumerable<Type> 使用 Autofac

[英]Resolve all classes that annotated with Attribute as IEnumerable<Type> using Autofac

我有 3 個用 Attribute 注釋的類


[MyAttribute("xyz")]
class Class1
{}
//... other classes annotated with MyAttribute

我注冊了所有類型

IContainer container ;
var builder = new ContainerBuilder();

//register all types annotated by MyAttribute
Assembly assembly = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly)
    .Where(t => t.GetCustomAttribute<MyAttribute>() != null);

//other registered classes /services

container = builder.Build();

嘗試解決:

//what this line(s) can be for only class that annotated by attribute
IEnumerable<Type> types =  container.Resolve<IEnumerable<Type>>(); 

這個答案沒有幫助

如何解決和獲取IEnumerable<Type>

當你這樣做時:

builder.RegisterAssemblyTypes(assembly)
    .Where(t => t.GetCustomAttribute<MyAttribute>() != null);

在幕后,它基本上是這樣做的:

var types = assembly.GetTypes().Where(t => t.GetCustomAttribute<MyAttribute>() != null)
foreach(var type in types)
{
  builder.RegisterType(type).AsSelf();
}

假設您有三種類型的屬性: MyClass1MyClass2MyClass3 這意味着注冊基本上與:

builder.RegisterType<MyClass1>();
builder.RegisterType<MyClass2>();
builder.RegisterType<MyClass3>();

在任何時候,您都不會向 Autofac 注冊類型Type

老實說,我建議不要使用 Autofac 注冊超級通用的基本類型,例如stringType 我會創建一個獲取信息的工廠。 這樣,如果我需要有兩個不同的Type列表,那么我可以通過使用兩個不同的工廠接口輕松地將它們分開。

但是假設您無論如何都想這樣做,您實際上必須注冊Type而不是MyClass1或其他什么。 Autofac 不會開箱即用。 你必須自己做。

我沒有通過編譯器運行它,但它應該是這樣的......

var types = assembly.GetTypes().Where(t => t.GetCustomAttribute<MyAttribute>() != null)
foreach(var type in types)
{
  builder.RegisterInstance(type).As<Type>();
}

這個想法是你想要注冊Type以便你可以列出這些東西,而不是你試圖實例化你找到的東西。 您不想RegisterType(type)因為這基本上意味着您希望 Autofac 能夠創建type的實例,而不是跟蹤這些類型的列表,以便您以后可以獲取它們 這種混亂是將其置於您自己創建的工廠背后的另一個重要原因。

真的很簡單:

public class TypeFactory
{
  public IEnumerable<Type> Types {get;}
  public TypeFactory(IEnumerable<Type> types)
  {
     this.Types = types;
  }
}

然后:

var types = assembly.GetTypes().Where(t => t.GetCustomAttribute<MyAttribute>() != null)
var factory = new TypeFactory(types);
builder.RegisterInstance(factory);

然后解析TypeFactory而不是嘗試直接解析IEnumerable<Type>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM