【问题标题】:Inject database context into classes using interface使用接口将数据库上下文注入类
【发布时间】: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


【解决方案1】:

更新

事后我意识到这是不可能的。

由于我已经设置了 Ninject,因此在构造函数中任何有上下文的地方都会有一个已经初始化的上下文,所以我不需要抽象类。

我的服务类将如下所示:

public class RecipeTypesIndexService : IRecipeTypeIndexService
{
    private Context context { get; }

    public RecipeTypesIndexService(Context context) : base(context)
    {
        this.context = context;
    }

    public IEnumerable<RecipeType> GetAll()
    {
        return context.RecipeTypes.AsEnumerable();
    }
}

我根本不需要抽象基类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 2019-08-23
    • 2020-11-15
    • 2022-07-31
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多