SimpleInjector - IoC/DI库


MIT
Windows
C#

软件简介

SimpleInjector是一个基于.NET3.5的、简单易用的IoC/DI库。

SimpleInjector完全支持基于代码配置,对不太熟悉IoC/DI框架的开发人员是一种不错的选择。

使用

public class UserController : Controller
{
    private readonly IUserRepository repository;
    private readonly ILogger logger;

    // Use constructor injection for the dependencies
    public UserService(IUserRepository rep, ILogger logger)
    {
        this.repository = rep;
        this.logger = logger;
    }

    // implement UserController methods here.
}

配置

protected void Application_Start(object sender, EventArgs e) 
{
    // 1. Create a new Simple Injector container
    var container = new Container();

    // 2. Configure the container (register)
    container.Register();

    container.RegisterSingle(() => new CompositeLogger(
        container.GetInstance(),
        container.GetInstance()
    ));

    // 3. Optionally verify the container's configuration.
    container.Verify();

    // 4. Register the container as MVC3 IDependencyResolver.
    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}