具有MVC和WebAPI的简单注入器

时间:2017-03-28 13:36:53

标签: asp.net-mvc asp.net-web-api simple-injector

我有一个C#项目,包括我想使用Simple Injector的WebAPI和MVC控制器。 https://simpleinjector.readthedocs.io/en/latest/mvcintegration.html上的Simple Injector文档将MVC的Application_Start方法显示为

protected void Application_Start(object sender, EventArgs e) {
    // Create the container as usual.
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

    // Register your types, for instance:
    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

    // This is an extension method from the integration package.
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

    container.Verify();

    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}

https://simpleinjector.readthedocs.io/en/latest/webapiintegration.html为WebAPI显示以下内容

protected void Application_Start() {
    // Create the container as usual.
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

    // Register your types, for instance using the scoped lifestyle:
    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

    // This is an extension method from the integration package.
    container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

    container.Verify();

    GlobalConfiguration.Configuration.DependencyResolver =
    new SimpleInjectorWebApiDependencyResolver(container);

    // Here your usual Web API configuration stuff.
}

我如何编写Application_Start代码,以便在WebAPI和MVC控制器中使用Simple Injector?

1 个答案:

答案 0 :(得分:3)

你可以像这样把代码放在一起:

protected void Application_Start(object sender, EventArgs e) {
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

    // User MVC integration
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

    // Use Web API integration
    container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

    container.Verify();

    // Plug in Simple Injector into MVC
    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

    // Plug in Simple Injector into Web API
    GlobalConfiguration.Configuration.DependencyResolver =
        new SimpleInjectorWebApiDependencyResolver(container);
}