如何使用SimpleIOC注册通用存储库

时间:2013-10-10 02:14:11

标签: c# dependency-injection inversion-of-control repository-pattern

如何在SimpleIOC中注册通用存储库?

  public interface IRepository<T>
  {

  }

  public class Repository<T> : IRepository<T>
  {

  }

  SimpleIoc.Default.Register<IRepository, Repository>(); //Doesn't work, throws error


 Error  1   Using the generic type 'AdminApp.Repository.IRepository<TModel>' requires 1 type arguments  C:\Application Development\AdminApp\AdminApp.Desktop\ViewModel\ViewModelLocator.cs  55  44  AdminApp.Desktop

我也试过了:

    SimpleIoc.Default.Register<IRepository<>, Repository<>>(); //Doesn't work either
     Error  1   Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement   C:\Application Development\AdminApp\AdminApp.Desktop\ViewModel\ViewModelLocator.cs  55  17  AdminApp.Desktop

1 个答案:

答案 0 :(得分:4)

我不相信GalaSoft.MvvmLight.Ioc.SimpleIocsource code)支持开放通用实施。您需要创建封闭的实现并分别注册它们:

public interface IRepository<T> where T : class { }

public class A { }
public class B { }

public class RepositoryA : IRepository<A> { }
public class RepositoryB : IRepository<B> { }

SimpleIoc.Default.Register<IRepository<A>, RepositoryA>();
SimpleIoc.Default.Register<IRepository<B>, RepositoryB>();

我建议您考虑转移到更成熟的库,例如SimpleInjector,它对泛型有广泛的支持。

SimpleInjector的代码简单如下:

container.RegisterOpenGeneric(typeof(IRepository<>), typeof(Repository<>));