简体   繁体   English

Autofac和RegisterGeneric-限制允许的泛型

[英]Autofac and RegisterGeneric - limit allowed generics

Let's say that I have a generic registration with Autofac: 假设我在Autofac进行了通用注册:

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

Now (I)Injectator has single generic. 现在(I)Injectator具有单个泛型。 But I don't want every possible class or struct to be allowed as generic. 但是我不希望所有可能的类或结构都被通用。

I only want it for classes, that inherit from some specified class: 我只想要从某些指定的类继承的类:

class JustClass { // not allowed
}

class SpecialClass : InjectableClass { // allowed
}

The easiest way would be to add a constraint on your generic interface : 最简单的方法是在通用接口上添加约束:

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

This way .net won't allow you to get an invalid type. 这样,.net将不允许您获得无效的类型。

If you can't do this, there is no easy way to change the behavior of RegisterGeneric one way I can see is to subscribe to the OnActivated event and throw an exception : 如果您不能执行此操作,则没有简单的方法可以更改RegisterGeneric的行为,我可以看到的一种方法是订阅OnActivated事件并引发异常:

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");
            }
        });

If you don't want to throw an exception you can implement your own IRegistrationSource . 如果您不想引发异常,则可以实现自己的IRegistrationSource You can have a look at the source code of the native OpenGenericRegistrationSource which resolves open generic types. 您可以查看本机OpenGenericRegistrationSource的源代码,该源代码可以解析开放的泛型类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM