Reputation: 9895
As a newbie to Autofac, I'm trying to figure out how to register my Repository for my Controllers. The Repository takes a web service in its constructor to communicate with the server. This application is multi-tenant and the tenant name is accessed in the MVC route data. Since I can't access the route data within global.asax like most of the examples, where do I inject this dependency and what would the code look like?
Upvotes: 1
Views: 637
Reputation: 17272
Try the Autofac.Features.Indexed.IIndex<K, V>
type which allows you to build a mapping of keys to implementations.
public enum RepositoryWebServices { ServiceA, ServiceB, ServiceC }
builder.RegisterType<MyServiceA>().Keyed<IWebService>(RepositoryWebServices.ServiceA);
builder.RegisterType<MyServiceB>().Keyed<IWebService>(RepositoryWebServices.ServiceB);
builder.RegisterType<MyServiceC>().Keyed<IWebService>(RepositoryWebServices.ServiceC );
public MyRepository : IRepository
{
IIndex<RepositoryWebServices, IWebService> _webServices;
public MyRepository(IIndex<RepositoryWebServices, IWebService> webServices)
{
_webServices = webServices;
}
public UseWebService(string tenant)
{
IWebService webService = _webServices[(RepositoryWebServices)Enum.Parse(typeof(RepositoryWebServices), tenant)];
// use webService
}
}
Upvotes: 1