【发布时间】: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<...>作为你的 DataContext 但我会假设你的函数不会生成上下文。
标签: c# dependency-injection asp.net-core-2.0 asp.net-core-webapi