【问题标题】:LightInject equivalent lifetime in .netcore DI container.netcore DI 容器中的 LightInject 等效寿命
【发布时间】:2022-01-03 11:42:24
【问题描述】:

从“LightInject”迁移到 .netcore DI 容器。

以下 LightInject 相关注册的 .netcore DI 容器 等效项是什么?

 a. container.RegisterConstructorDependency<IBar>((factory, parameterInfo) => new Bar()); 

 b. container.RegisterInstance<Func<string, string>>
        ((username, password) => new MemCache(userId, password, container.GetInstance<IBusinessLogic>())); 

【问题讨论】:

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


    【解决方案1】:

    我相信 A 会是这样的:

    services.AddTransient<IBar>(container => new Bar());
    

    对于 B,如果您有一个已经存在的实例并且您只想注册,那么您可以执行以下操作:

    ISomething somethingInstance = new Something();
    services.AddSingleton<ISomething>(somethingInstance);
    

    但看起来你真的想注册一个工厂,所以我建议这样:

    services.AddScoped<Func<string, string, MemCache>>(ctx => (username, password) => new MemCache(username, password, ctx.GetRequiredService<IBusinessLogic>()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2021-06-03
      • 1970-01-01
      • 2018-02-25
      相关资源
      最近更新 更多