【发布时间】:2017-06-11 03:32:08
【问题描述】:
我希望将数据库上下文注入到所有实现我的接口similar to this post 的类中。
我有什么
public abstract class Service
{
public Service(Context context)
{
Context = context;
}
public Context Context { get; }
}
每个服务类都有一个带有方法的接口
interface IRecipeTypeIndexService
{
IEnumerable<RecipeType> GetAll();
}
所有的服务类都会继承抽象的Service类,所以我现在的具体类是这样的
public class RecipeTypesIndexService : Service, IRecipeTypeIndexService
{
public RecipeTypesIndexService(Context context) : base(context)
{
}
public IEnumerable<RecipeType> GetAll()
{
return Context.RecipeTypes.AsEnumerable();
}
}
我的 ninject 绑定看起来像
Kernel.Bind<DbContext>().ToSelf().InRequestScope();
Kernel.Bind<Service>().ToSelf().InRequestScope();
我想做的是让我的接口IRecipeTypeIndexService和我创建的其他服务接口继承另一个接口IService,这是Ninject绑定到抽象Service类,所以所有实现的具体类IWhateverService 必须有一个将数据库上下文注入基类的构造函数,所以我的具体类如下所示:
public class RecipeTypesIndexService : IRecipeTypeIndexService
{
public RecipeTypesIndexService(Context context) : base(context)
{
}
public IEnumerable<RecipeType> GetAll()
{
return Context.RecipeTypes.AsEnumerable();
}
}
这可能吗?这是我第一次使用 Ninject,而且我是使用依赖注入的新手。
【问题讨论】:
-
我认为您需要在基类中的 Context 属性中添加一个私有设置器: public Context Context { get;私人套装; }
-
无论如何它都是私有集,因为它没有设置器并且在构造函数中设置
-
Context = context 将不起作用,因为 Context 属性是只读的(它只有一个 getter)
-
在没有设置器的情况下,它可以在构造函数中设置。我有调用具体服务和调用数据库的集成测试。和只读属性一样
标签: c# inheritance dependency-injection ninject.web.mvc