So Im using autofac in a MVC so my controllers can have there dependencies injected on there constructor, I have in my Global.asax I have the following snippet of code, which works.
// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<PurchaseOrderSearchService>().As<IPurchaseOrderSearchService>().WithParameter("context", new PurchaseOrderManagerContext());
// Set the dependency resolver to be Autofac.
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
The problem is I don't want to do builder.RegisterType over and over again, for all my Services. So how do I do that?
I think the kind of thing I want is
builder.RegisterAssemblyTypes(foo)
.Where(t => t.Name.EndsWith("Services"))
.WithParameter("context", new PurchaseOrderManagerContext());
But no idea what foo should be. Or if RegisterAssemblyTypes is correct way. I know coding by convention is the solution but not sure what the convention is. All my services will end int word Service and will have interface
so FooService will have interface IFooService and BarService will have interface IBarService
Should also point out that all the services live in a class library called PurchaseOrderManager.Service
You're on the right track. "Foo" should be the assembly containing the types to register - if you're using a single assembly then the following should work:
The
.AsImplementedInterfaces()is needed to register them asIFooService- without it, they would only be registered asFooServiceetc.If your classes live in a separate assembly, I would normally recommend you define an autofac module within that assembly:
Then register this in your web application:
Alternatively, use my original suggestion but explicitly specify the assembly containing the services:
You just need to pick any class which exists in that assembly.