1

如何向 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
4

1 回答 1

4

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

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<>));
于 2013-10-10T09:56:03.947 回答