如何在不更改/添加构造函数的情况下使用依赖项注入

时间:2019-02-12 15:00:35

标签: c# dependency-injection

我有以下asp.net c#代码

{      
    public class Test
    {

    ISomeService _someService;

    public Test()
    {
    }

    public void DoSomething()
    {
    _someService.Do();
    }
}

我需要向Test类提供ISomeService,但我不知道该怎么做。我不允许添加其他构造,例如,整个问题都会消失

public Test(ISomeService someService)
{
    _someService = someService;
}

我尝试使用setter注入或方法注入,但是没有成功。

SomeService类中ISomeService的实现也使用构造函数注入,例如

public SomeService(IService1 service1, Iservice2 service2)

不确定在这里做什么

这里是完整代码

 public class Startup
    {
        private IService _service;

        public Startup()
        {

        }

        public Startup(IService service)
        {
            _service = service;
        }


        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            var container = new UnityContainer();            
            container.RegisterType<IService, Service>();
            config.DependencyResolver = new UnityDependencyResolver(container);

            app.UseWebApi(config);

            _service.DoSomething());

        }
    }

_service为空

2 个答案:

答案 0 :(得分:0)

我建议您使用工厂创建对象。那将在构造函数上注入一个ISomeService实例。

然后在工厂的CreateTest()方法中直接设置ISomeService属性。

public class Factory
{
    private readonly ISomeService someService;

    public Factory(ISomeService someService)
    {
        this.someService = someService ?? throw new ArgumentNullException(nameof(someService));
    }
    public TestClass CreateTestClass()
    {
        var instance = new TestClass();
        instance.SomeService = this.someService;
        return instance;
    }

}

您应该注意,大多数DI提供程序都内置了允许工厂语义的功能,而无需创建自己的工厂。

答案 1 :(得分:0)

我最终要做的是这个

var serviceCollection = new ServiceCollection();

serviceCollection.AddTransient<IService, Service>();

// create service provider
var serviceProvider = serviceCollection.BuildServiceProvider();

_service = ActivatorUtilities.CreateInstance<Service>(serviceProvider);

_service.DoSomething();

感谢这个答案Dependency Injection with classes other than a Controller class