I have the following IRoleClient and RoleClient but it varied with different routePrefix.
How to inject IRoleClient into AdminRoleController and UserRoleController with different routePrefix using dependency injection "unity". Or other approaches are able to achieve it?
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;
}
}
And here are my register in unity
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))));
You can inject object into constructor that was been register with some name.
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;
}
}