![](/img/trans.png)
[英]How to register a class with a dependency injected constructor? (SimpleIoC)
[英]How To Register Generic Repository With SimpleIOC
如何在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
我不相信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<>));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.