我在尝试注册“自动”某些开放泛型类型的所有已关闭实现时遇到Autofac问题,如果这些是在引用的程序集中定义的话。 如果在主程序集中定义了所有内容,则一切正常。
Assembly mainExecAssembly = System.Reflection.Assembly.GetEntryAssembly();
List<Assembly> assemblies= new List<Assembly>();
assemblies.Add(mainExecAssembly);
builder.RegisterAssemblyTypes(assemblies.ToArray())
.AsClosedTypesOf(typeof(IMyOpenGenericTypeHandler<>))
.AsImplementedInterfaces();
但是如果这些是在引用的程序集中定义的(在引导程序中迭代并加载):
Assembly mainExecAssembly = System.Reflection.Assembly.GetEntryAssembly();
List<Assembly> assemblies= new List<Assembly>();
assemblies.Add(mainExecAssembly);
AssemblyName[] aNames = mainExecAssembly.GetReferencedAssemblies();
foreach (var an in aNames)
{
Assembly a = Assembly.Load(an.FullName);
assemblies.Add(a);
}
builder.RegisterAssemblyTypes(assemblies.ToArray())
.AsClosedTypesOf(typeof(IMyOpenGenericTypeHandler<>))
.AsImplementedInterfaces();
然后没有注册开放泛型类型的具体实现。
具体类型如下:
public class MyExtendedTypeHandler: IMyOpenGenericTypeHandler<MyExtendedType>
{
public MyExtendedTypeHandler()
{
}
public void Handle(MyExtendedType handle)
{
}
}
public interface IMyOpenGenericTypeHandler<T> where T: IMyT
{
void Handle(T handle);
}
public interface IMyT
{
Guid Id { get; set; }
}
public class MyType: IMyT
{
public Guid Id { get; set; }
}
public class MyExtendedType: MyType
{
public string Name { get; internal set; }
public MyExtendedType(string name)
{
Id = Guid.NewGuid();
Name = name;
}
}