在构造函数中使用不同参数的依赖注入(C#)

时间:2017-05-28 09:23:10

标签: c# dependency-injection unity-container

我有以下IRoleClient和RoleClient,但它随着不同的routePrefix而变化。

如何使用依赖注入" unity"将IRoleClient注入具有不同routePrefix的AdminRoleController和UserRoleController。或者其他方法能够实现吗?

public interface IRoleClient
{
    Task<PagedResponse<RoleModel>> GetRolesAsync(GetRolesRequest request);

    Task<CreateRoleResponse> CreateRoleAsync(CreateRoleRequest request);

    Task<UpdateRoleResponse> UpdateRoleAsync(int roleId, UpdateRoleRequest request);
}

public sealed class RoleClient : IRoleClient
{
    private readonly string _routePrefix; 
    public RoleClient(string serverBaseUrl, string routePrefix) : base(serverBaseUrl)
    {
        _routePrefix = routePrefix;
    }
    Task<PagedResponse<RoleModel>> IBackOfficeRoleClient.GetRolesAsync([FromUri] GetRolesRequest request)
    {
        return GetAsync<PagedResponse<RoleModel>>(_routePrefix, request);
    }

    async Task<CreateRoleResponse> IBackOfficeRoleClient.CreateRoleAsync(CreateRoleRequest request)
    {
        var res = await PostJsonAsync(_routePrefix, request);
        return await ReadJsonContentAsync<CreateRoleResponse>(res.Content);
    }

    Task<UpdateRoleResponse> IBackOfficeRoleClient.UpdateRoleAsync(int roleId, UpdateRoleRequest request)
    {
        return PutAsync<UpdateRoleResponse>($"{_routePrefix}/{roleId}", request);
    }
}

public class AdminRoleController()
{
    private readonly IRoleClient _roleClient;
    public AdminRoleController(IRoleClient roleClient)
    {
        _roleClient = roleClient;
    }
}

public class UserRoleController()
{
    private readonly IRoleClient _roleClient;
    public UserRoleController(IRoleClient roleClient)
    {
        _roleClient = roleClient;
    }
}

这是我的团结登记

container.RegisterType<IRoleClient, RoleClient>(ReuseWithinResolve, new InjectionConstructor(Config.ApiUrl,"/api/adminRoles"));
container.RegisterType<IRoleClient, RoleClient>(ReuseWithinResolve, new InjectionConstructor(Config.ApiUrl,"/api/userRoles"));

container.RegisterType<Func<string, IRoleClient>>(
            new InjectionFactory(c =>
                new Func<string, IRoleClient>(name => c.Resolve<IRoleClient>(name))));

1 个答案:

答案 0 :(得分:1)

您可以将对象注入到已使用某个名称注册的构造函数中。

container.RegisterType<IRoleClient, RoleClient>("SomeRegisterName", ReuseWithinResolve, new InjectionConstructor(Config.ApiUrl, "/api/adminRoles"));

....

public class AdminRoleController()
{
    private readonly IRoleClient _roleClient;
    public AdminRoleController([Dependency("SomeRegisterName")]IRoleClient roleClient)
    {
        _roleClient = roleClient;
    }
}