[Original] dependency injection in ASP. NET web API using autofac
Summary
Use autofac in ASP. NET Web APIs
Install autofac. webapi through nuget. (Of course, you must first install autofac. dll ).
PM> install-package autofac. webapi
REFERENCE The following namespace.
using Autofac;
using Autofac.Integration.WebApi;
Configure autofac according to the following code.
public static class Bootstrapper
{
public static void Run()
{
SetAutofacWebAPI();
}
private static void SetAutofacWebAPI()
{
var configuration = GlobalConfiguration.Configuration;
var builder = new ContainerBuilder();
// Configure the container
builder.ConfigureWebApi(configuration);
// Register API controllers using assembly scanning.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<DefaultCommandBus>().As<ICommandBus>()
.InstancePerApiRequest();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>()
.InstancePerApiRequest();
builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>()
.InstancePerApiRequest();
builder.RegisterAssemblyTypes(typeof(CategoryRepository)
.Assembly).Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().InstancePerApiRequest();
var services = Assembly.Load("EFMVC.Domain");
builder.RegisterAssemblyTypes(services)
.AsClosedTypesOf(typeof(ICommandHandler<>))
.InstancePerApiRequest();
builder.RegisterAssemblyTypes(services)
.AsClosedTypesOf(typeof(IValidationHandler<>))
.InstancePerApiRequest();
var container = builder.Build();
// Set the WebApi dependency resolver.
var resolver = new AutofacWebApiDependencyResolver(container);
configuration.ServiceResolver.SetResolver(resolver);
}
}
Call bootstrapper. Run () in application_start ().
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
//Call Autofac DI configurations
Bootstrapper.Run();
}
Autofac. mvc4
Autofac ASP. net mvc integration has been upgraded to mvc4. Nuget pacakgeautofac. mvc4. It provides dependency injection (excluding Web APIs) in ASP. NET mvc4 ). There is no syntax difference between autofac. mvc3 and autofac. mvc4.
Source code
Http://efmvc.codeplex.com/
A sample web program is used to demonstrate ASP. net mvc, EF code first, and architecture practices.
Related Resources:
Autofac official http://code.google.com/p/autofac/
Autofac ASP. NET mvc3 ingetation http://code.google.com/p/autofac/wiki/Mvc3Integration