通过通用接口查找类

时间:2015-04-27 14:01:27

标签: c# generics

在我的应用程序中,我有以下类来获取接口的实例:

public static class ServiceProvider
{
    private static readonly Dictionary<Type, dynamic> _serviceStorage;
    private static readonly object _serviceLock;

    static ServiceProvider()
    {
        _serviceLock = new object();
        _serviceStorage = new Dictionary<Type, dynamic>();
    }

    public static T GetService<T>()
    {
        Type serviceType = typeof (T);
        lock (_serviceLock)
        {
            if (!_serviceStorage.ContainsKey(serviceType))
            {
                _serviceStorage.Add(serviceType, (T) CreateService(serviceType));
            }
        }
        return _serviceStorage[serviceType];
    }

    private static dynamic CreateService(Type serviceType)
    {
        Type implementationType = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .FirstOrDefault(type => serviceType.IsAssignableFrom(type) && type.IsClass);
        if (implementationType == null)
            throw new NullReferenceException();
        return Activator.CreateInstance(implementationType);
    }
}

实现类必须实现提供的接口并具有无参数构造函数。

例如,我的接口IEventRegistrationService类似于:

public interface IEventRegistrationService
{
  void Register(string name, Action<object> callback);
}

,实现类看起来像:

internal class EventRegistrationService : IEventRegistrationService
{
  public void Register(string name, Action<object> callback)
  {
     // Register the action with this name...
  }
}

我的服务用法如下:

IEventRegistrationService service = ServiceProvider.GetService<IEventRegistrationService>();

现在我有一个界面实例。一切正常,直到这里。

现在我想让IEventRegistrationService接口通用,以在回调操作中使用正确的类型。 “新”界面应如下所示:

public interface IEventRegistrationService<T>
{
  void Register(string name, Action<T> callback);
}

实现类现在看起来像:

internal class EventRegistrationService<T> : IEventRegistrationService<T>
{
   public void Register(string name, Action<T> callback)
   {
      // Register the action with this name...
   }
}

用法应该是:

IEventRegistrationService<string> service = ServiceProvider.GetService<IEventRegistrationService<string>>();

但是使用这个泛型,我在CreateService方法的ServiceProvider - 类中得到了一个异常。

声明:

 Type implementationType = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(assembly => assembly.GetTypes())
                .FirstOrDefault(type => serviceType.IsAssignableFrom(type) && type.IsClass);

返回null。

我想这是因为.IsAssignableFrom(type),但我不知道如何解决这个问题。

如何检查类是否实现了通用接口?

编辑:

我不知道预期的接口类型。

0 个答案:

没有答案