繁体   English   中英

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

[英]Using Dependency Injection to Initialize values via Constructors

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

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通过构造函数初始化值。

是否可以使用接口引用_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容器(其组成根目录)中注册。

我也建议回顾

依赖注入代码的气味:将运行时数据注入组件

获得关于如何重构UserService以避免当前问题的另一种观点。

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

简单的工厂示例:

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;
    }
} 

见我的小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM