【问题标题】:Null object when Injecting Repository with Asp.Net Core 2使用 Asp.Net Core 2 注入存储库时为空对象
【发布时间】:2018-08-24 07:34:10
【问题描述】:

我的 Func 无法成功通过。我在我的 startup.cs 中注入 webapi

services.AddDbContext<MyDataContext>(
    options => options.UseSqlServer(DbGlobals.DevDatabase,
    b => b.MigrationsAssembly("Services.Data.EF")));

services.AddTransient<Func<IMyDataContext>, Func<MyDataContext>>();
services.AddTransient(provider => new Func<IMyDataContext>(() => provider.GetService<IMyDataContext>()));

然后在我的控制器中,我有以下内容;

private ClientService _service;

public ClientController(Func<IMyDataContext> context)
{
    _service = new ClientService(context);
}

我的服务中的方法是;

private readonly Func<IMyDataContext> _contextFactory;

public ClientService(Func<IMyDataContext> contextFactory)
{
    _contextFactory = contextFactory;
}

public void AddClient(Client model, string userName)
{
    Func<Client> func = delegate
    {
        using (var context = _contextFactory())
        {
             ....
        }
    };

    return this.Execute(func);
}

现在从调试中,如果我检查控制器注入,我可以看到 Func 已传入并且处于服务级别 2。但是,当在 context = _contextFactory() 的 using 语句中使用它时,它变为 null?

请知道我在这里做错了什么?

【问题讨论】:

  • 只是为了澄清。是context == null 还是_contextFactory == null
  • context = null,即调用_contextFactory()
  • 我不确定你为什么使用 Func&lt;...&gt; 作为你的 DataContext 但我会假设你的函数不会生成上下文。

标签: c# dependency-injection asp.net-core-2.0 asp.net-core-webapi


【解决方案1】:

您的定义略有错误。您需要定义 IDataContext 和 DataContext 是相关的:

services.AddTransient<IDataContext, DataContext>();

现在 DI 知道如何创建 IDataContext。现在你的方法只需要在使用 func 时使用服务提供者来创建它:

services.AddTransient<Func<IMyDataContext>>(provider => () 
        => provider.GetService<IMyDataContext>());

现在,当您的服务创建时,DI 将注入您的 Func

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 2019-12-21
    • 2012-01-27
    • 2018-06-20
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多