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?
+1
A:
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
}
}
Todd Smith
2010-08-26 23:15:52
Todd, thanks this is close to what I'm after. Where would be the best place to call UseWebService? I basically need to call this once to initialize the web service and then my repository methods can do what they need to do. The problem is I need the route data to get the tenant so I don't think I can do this in global.asax. Right now, I call UseWebService by overriding the Initialize method in a base controller because I can get to the route data. This works but just doesn't feel right.
SaaS Developer
2010-08-28 15:08:41