首页 > 解决方案 > 使用依赖注入通过构造函数初始化值

问题描述

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

该类UserService具有构造函数来初始化其参数的值。

我正在UserService通过 DI 在另一个类中使用。

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

标签: c#dependency-injectionconstructor

解决方案


处理这个问题的最简单方法是注入工厂而不是实例。这将允许您在运行时提供参数。

简单的工厂示例:

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

看我的小提琴


推荐阅读