如何在MVC . net Core的依赖注入框架中利用相同的对象实例

本文关键字:实例 对象 框架 注入 MVC net 依赖 Core | 更新日期: 2023-09-27 18:11:29

我正在利用Mvc . net Core中附带的依赖注入框架。有一种情况,我想使用服务类的相同实例,但通过该类实现的两个不同接口。我使用AddScope将类和接口连接起来。在我的例子中,使用AddSingleton和在Startup类中直接实例化MyServiceClass都不是选项。

下面的代码示例说明了我的场景。我的挑战/问题是,我如何才能确保MyOtherClass的构造函数通过它的两个参数接收到MyServiceClass的相同实例。

using System;
namespace TestNamespace {
    public interface Interface1 { void DoThisThing(); }
    public interface Interface2 { void DoThatThing(); }
    public class MyServiceClass : Interface1, Interface2
    {
        public MyServiceClass()
        {
        }
        public void DoThisThing()
        {
            Console.Write("Keep thinking differently. (Steve Jobs)");
        }
        public void DoThatThing()
        {
            Console.Write("Keep calm and carry on.");
        }
    }
    public class MyOtherClass
    {
        private Interface1 _service1;
        private Interface2 _service2;
        public MyOtherClass(Interface1 service1, Interface2 service2)
        {
            _service1 = service1;
            _service2 = service2;
        }
        public void DoAllThingsTogether()
        {
            _service1.DoThisThing();
            _service2.DoThatThing();
        }
    }

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddScoped<Interface1, MyServiceClass>();
            services.AddScoped<Interface2, MyServiceClass>();
            services.AddMvc();
        }
    } }

如何在MVC . net Core的依赖注入框架中利用相同的对象实例

   public void ConfigureServices(IServiceCollection services)
   {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);
        services.AddScoped<MyServiceClass>();
        services.AddScoped<Interface1>(provider =>
        {
            return provider.GetService<MyServiceClass>();
        });
        services.AddScoped<Interface2>(provider =>
        {
            return provider.GetService<MyServiceClass>();
        });
        services.AddMvc();
    }