【问题标题】:Creating a DbContext with custom constructor with injected parameter in Entity Framework在实体框架中使用带有注入参数的自定义构造函数创建 DbContext
【发布时间】:2016-06-26 19:46:09
【问题描述】:

我正在处理代码优先数据库,但是当我尝试执行“更新数据库”时,我收到以下错误。

The target context 'AllMid.DL.Repository.Implementation.AllMidContext' is not constructible. 
Add a default constructor or provide an implementation of IDbContextFactory.

现在对我来说很明显,问题在于我没有默认构造函数或 IDbContextFactory 接口的实现,但在我使用的示例项目中,我看到这两者都没有。有谁知道该怎么做?

我目前有一个类似的 DbContext。

internal class AllMidContext : DbContext, IAllMidContext
{
    public DbSet<TreeEntity> Tree { get; set; } 

    public AllMidContext(IConfigurationAccess configAccess) : base(configAccess.GetDefaultConnectionString())
    {
    }
}

configAccess 应该由结构映射注入。

还有一个像这样的 DataContextAccess 类

    internal class DataContextAccess : IDataContextAccess
    {
        private readonly IConfigurationAccess _configAccess;

        public DataContextAccess(IConfigurationAccess configAccess)
        {
            _configAccess = configAccess;
        }

        public IAllMidContext GetAllMidContext()
        {
            return new AllMidContext(_configAccess);
        }
    }

现在的问题是有没有办法在没有默认构造函数或工厂的情况下做到这一点?我的依赖注入将始终输入参数,所以我怎样才能让 EF 使用我的自定义构造函数?

【问题讨论】:

  • 我更感兴趣的是让它使用带有注入依赖项的客户构造函数,而不是创建默认构造函数。

标签: c# .net entity-framework


【解决方案1】:

我相信update-database 正在寻找一个没有输入的构造函数。您可以做的是编写一个没有输入的构造函数并在其主体中进行注入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多