Ninject "custom" DBContext 绑定

Ninject "custom" DBContext binding

我目前正在开发一个虚拟 MVC 项目(尝试一些新事物),但我在将 DatabaseContext 注入我的服务时遇到问题...

您可以在下面找到我的代码:

我的数据库上下文:

public class DatabaseContext : DbContext
{
    protected DatabaseContext() : base("DatabaseContext")
    {
    }

    public DbSet<MacAddress> MacAddresses { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

我想注入上下文的服务和界面:

public interface IMacAddressService
{
    List<MacAddress> GetAllMacAddresses();
}

public class MacAddressService : IMacAddressService
{
    private readonly DatabaseContext _context;

    public MacAddressService(DatabaseContext context)
    {
        this._context = context;
    }

    public List<MacAddress> GetAllMacAddresses()
    {
        return _context.MacAddresses.ToList();
    }
}

我可以在我的 IKernel 上应用什么绑定来正确地注入我的 DatabaseContext?

供您参考:

提前致谢!

您不使用任何抽象将 DatabaseContext 传递给您的服务,因此 Ninject 将在没有任何额外配置的情况下解析它。

如果您想显式配置绑定,可以使用 Bind<DatabaseContext>().ToSelf()

编辑

我刚刚注意到您的 DatabaseContext 构造函数受到保护

protected DatabaseContext() : base("DatabaseContext")
{
}

您需要使其成为 public 才能创建 DatabaseContext

的实例