2017-05-28 89 views
-1

我有以下IRoleClient和RoleClient,但它隨不同的routePrefix而變化。在構造函數(C#)中使用不同參數的依賴注入

如何使用依賴注入「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

你可以注入到對象的構造函數,是被一些名稱註冊登記。

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; 
    } 
} 
相關問題