【问题标题】:Dbcontext IDbset properties are null when injected in ServiceStack IoC注入 ServiceStack IoC 时,Dbcontext IDbset 属性为空
【发布时间】:2017-08-09 08:44:22
【问题描述】:

我已经在 ServiceStack 中使用标准容器注册了我的 DbContext,DbContext 被注入到服务中,但奇怪的是 IDbSet 属性是 null,所有其他属性都符合预期。

如果我在 Service 构造函数中新建 DbContext,IDbSet 属性会按照您的预期进行实例化,以证明 EF 的配置已正确设置。所有其他注册的服务都被正确注入,没有这种奇怪的行为。

我错过了什么?

public class AppHost : AppHostBase
{
    public override void Configure(Container container)
    {
        container.AddScoped<IDbContext, MyDataContext>();
        // Other registrations here omitted for brevity.
    }
}

public interface IDbContext : IDisposable
{
    IDbSet<MyEntity> MyEntity { get; set; }

    DbChangeTracker ChangeTracker { get; }
    DbContextConfiguration Configuration { get; }
    Database Database { get; }

    int SaveChanges();
    Task<int> SaveChangesAsync();
    Task<int> SaveChangesAsync(CancellationToken cancellationToken);

    DbEntityEntry<T> Entry<T>(T entity) where T : class;
}

【问题讨论】:

  • 在“newing-up”MyDataContext 时是否使用替代(即非无参数)构造函数?
  • 我只是忽略了注入的对象,并在构造函数中将字段设置为_dbcontext = new MyDataContext(),这样签名就不会改变。

标签: c# entity-framework servicestack ioc-container dbcontext


【解决方案1】:

我已经通过像这样更改注册来解决此问题;

container.Register&lt;IDbContext&gt;(i =&gt; new MyDataContext()).ReusedWithin(ReuseScope.Request);

我的原始注册container.AddScoped&lt;IDbContext, MyDataContext&gt;(); 是自动绑定注册类型的简写; container.RegisterAutoWiredAs&lt;MyDataContext,IDbContext&gt;().ReusedWithin(ReuseScope.Request);

我想知道 Func 容器是否在使用 AutoWired 时尝试解析 iDbSet 属性。这可以解释为什么它们最终为空。

【讨论】:

    猜你喜欢
    • 2013-03-29
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    相关资源
    最近更新 更多