[英]Resolve Generic Repository with Ninject
我有帶有GetRepository<T>
UnitOfWork,我需要用Ninject
解決它。
public TRepository GetRepository<TRepository>() where TRepository : class, IRepository
{
throw new NotImplementedException();
}
我使用MVC
並且將模塊加載到NinjectWebCommon.cs中 ,如下所示:
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
INinjectModule[] modules = { new CommonModule(), new ServicesModule(), new BusinessModule(), new DataModule() };
var kernel = new StandardKernel(modules);
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
任何想法如何獲取GetRepository
的實例? 我嘗試創建一個IResolver
並將其注入到UnitOfWork
並解決該泛型,但是我得到了null。
編輯:
我想更新解決方案:
public UnitOfWork(IDbContext context, IKernel resolver)
{
_context = context;
_resolver = resolver;
}
public TRepository GetRepository<TRepository>() where TRepository : class, IRepository
{
return (TRepository)_resolver.GetService(typeof(TRepository));
}
請注意,我使用的是IResolver的抽象而非具體實現,因此我不認為這是一種反模式(盡管我可能是錯的)。 我試圖找出如何使用IResolutionRoot解決此問題,如下面的答案所示。
編輯:
在閱讀了越來越多的文章之后,我想到了在使用泛型時這不是一種反模式。 避免泛型服務定位器的唯一合適解決方案是反射。 因此,我特別希望使用服務定位器而不是反射。
您問題的直接答案是在構造函數中聲明IKernel
(或更佳的是IResolutionRoot
)依賴項。 但是,請注意,對DI容器的依賴以及在類中對此容器的使用將被稱為服務位置,並且被視為反模式 。 您可能要考慮更改此設計。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.