使用依赖注入通过构造函数初始化值

时间:2019-09-09 23:59:58

标签: c# dependency-injection constructor

我有一个实现接口UserService的类IUserService

UserService类具有用于将值初始化为其参数的构造函数。

我正在通过DI在另一堂课中使用UserService

如何初始化UserService对象的值。

public class OfferService : IOfferService
{
    private IUserService _userService;
    private ISomeOtherService _someotherService;

    public OfferService(IUserService userService, ISomeOtherService someotherService)
    {
        _userService = userService;
        _someotherService = someotherService;
    }

    public bool SomeMethod()
    {
        string key = _someotherService.GetKey();
        string value = _someotherService.GetValue();

        //Calling parameterized constructor of UserService

        var user = new UserService(key,value);
    }
} 

是否可以使用接口引用_userService通过构造函数初始化值。

2 个答案:

答案 0 :(得分:1)

  

是否可以使用接口引用_userService通过构造函数初始化值。

简短答案:

如果您要解决必须手动进行任何新操作的情况,则需要进行设计,以使您的类明确定义其依赖关系并避免实现细节。

例如

public class OfferService : IOfferService {
    private readonly IUserService userService;

    public OfferService(IUserService userService) {
        this.userService = userService;            
    }

    public bool SomeMethod() {

        //...use userService

    }
} 


public class UserService : IUserService {

    public UserService(ISomeOtherService someotherService)
        string key = someotherService.GetKey();
        string value = someotherService.GetValue();

        //...
    }

    //...
}

并确保所有内容均已正确地在IoC容器(其组成根目录)中注册。

我也建议您审核

Dependency Injection Code Smell: Injecting runtime data into components

以另一种眼光看待如何重构UserService以避免当前问题。

答案 1 :(得分:1)

处理此问题的最简单方法是注入工厂而不是实例。这样您就可以在运行时提供参数。

简单的工厂示例:

public interface IUserServiceFactory
{
    IUserService GetUserService(string key, string val);
}

public class UserServiceFactory : IUserServiceFactory
{
    public IUserService GetUserService(string key, string val)
    {
        return new UserService(key, val);
    }
}

如何使用它:

public class OfferService : IOfferService
{
    private IUserServiceFactory _userServiceFactory;
    private ISomeOtherService _someotherService;

    public OfferService(IUserServiceFactory userServiceFactory, ISomeOtherService someotherService)
    {
        _userServiceFactory = userServiceFactory;
        _someotherService = someotherService;
    }

    public bool SomeMethod()
    {
        string key = _someotherService.GetKey();
        string val = _someotherService.GetValue();

        var user = _userServiceFactory.GetUserService(key, val);

        return false;
    }
} 

看到我的Fiddle