代码之家  ›  专栏  ›  技术社区  ›  Matthew Flynn

使用Asp注入存储库时,对象为Null。净核心2

  •  2
  • Matthew Flynn  · 技术社区  · 7 年前

    我无法使我的Func成功通过。我在启动时注入webapi。cs公司

    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=\u contextFactory()上的using语句中使用它时,它会变为null吗?

    你知道我做错了什么吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Simply Ged Saeed    7 年前

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

    services.AddTransient<IDataContext, DataContext>();
    

    现在DI知道了如何创建IDataContext。现在,您只需要在使用func时使用服务提供程序来创建方法:

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

    现在,创建服务时,DI将注入您的函数<&燃气轮机;