C# Autofac和RegisterGeneric-允许的限制泛型

C# Autofac和RegisterGeneric-允许的限制泛型,c#,.net,dependency-injection,autofac,C#,.net,Dependency Injection,Autofac,假设我在Autofac有一个通用注册: builder.RegisterGeneric(typeof(Injectator<>)) .As(typeof(IInjectator<>)) .SingleInstance(); 最简单的方法是在通用接口上添加约束: public interface IInjectator<T> where T : InjectableClass { } 如果不想引发异常,可以实现自己的I

假设我在Autofac有一个通用注册:

builder.RegisterGeneric(typeof(Injectator<>))
       .As(typeof(IInjectator<>))
       .SingleInstance();

最简单的方法是在通用接口上添加约束:

public interface IInjectator<T> 
    where T : InjectableClass 
{ }

如果不想引发异常,可以实现自己的
IRegistrationSource
。您可以查看本机的源代码,它解析开放泛型类型。

我使用了constraint way。
public interface IInjectator<T> 
    where T : InjectableClass 
{ }
builder.RegisterGeneric(typeof(Foo<>))
        .As(typeof(IFoo<>))
        .OnActivated(e =>
        {
            Boolean isValid = e.Component.Services
                .OfType<IServiceWithType>()
                .Where(s => s.ServiceType.IsConstructedGenericType
                            && s.ServiceType.GetGenericTypeDefinition() == typeof(IFoo<>)
                            && s.ServiceType.GetGenericArguments()[0].IsAssignableTo<IBar>())
                .Any();

            if (!isValid)
            {
                throw new Exception("boom");
            }
        });