【问题标题】:Autofac: Open generics and base interfacesAutofac:开放泛型和基本接口
【发布时间】:2013-10-31 14:00:42
【问题描述】:

鉴于以下接口和类,Autofac 中有没有办法

  • 为所有具有ProviderAttribute 的类注册Provider<T>,其中T 是此类的类型(考虑注册开放泛型并使用Autofac 的MakeGenericType() 解析它们)
  • 将这些注册的提供者作为,鼓,IEnumerable<IProviderBase> 注入到其他类的构造函数中

概述:

public class ProviderAttribute : Attribute { }

public interface IProviderBase
{
    Type Type { get; }
}

public interface IProvider<T> : IProviderBase
{
    DoSomething(T t);
}

public class Provider<T> : IProvider<T>
{
    public Type Type
    {
        get { return typeof (T); }
    }

    public DoSomething(T t)
    {
        //...
    }
}

【问题讨论】:

    标签: autofac open-generics


    【解决方案1】:

    我想出了一个粗略的解决方案:

    var types = GetProviderTypes();
    
    foreach (var type in types)
    {
        var t = typeof (Provider<>).MakeGenericType(type);
        builder.RegisterType(t).As<IProviderBase>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2014-11-25
      • 2013-05-21
      • 1970-01-01
      相关资源
      最近更新 更多