[英]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.