Autofac

De Banane Atomic
Aller à la navigationAller à la recherche

Description

Conteneur d'Inversion of Control pour ASP.NET Core et .NET 4.5.1+.

Exemple

Cs.svg
var builder = new ContainerBuilder();

builder.RegisterType<MyRepository>().As<IMyRepository>();
builder.RegisterType<Logger>().As<ILogger>();
builder.RegisterType<MyService>();

IContainer container = builder.Build();

// instead of instanciate MyService, ask the container
// container will instanciate MyService and resolve all the dependancies (ILogger, IMyRepository)
var myService = container.Resolve<MyService>();

Web API 2

Installer le package NuGet Autofac.WebApi2

App_Start\WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
    var builder = new ContainerBuilder();

    // Register your Web API controllers
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

    IContainer container = builder.Build();

    // Set the dependency resolver to be Autofac
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);