.Net Core Mvc中使用SimpleInjector

发布于 2017-07-07  174 次阅读


1.首先在Startup.cs中声明一个全局变量

private Container container = new Container();

2.在ConfigureServices方法中添加这几句

      services.AddSingleton(new SimpleInjectorControllerActivator(container));
      services.AddSingleton(new SimpleInjectorViewComponentActivator(container));
      services.UseSimpleInjectorAspNetRequestScoping(container);

3.添加一个方法

        private void InitializeContainer(IApplicationBuilder app)
        {
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
            // Add application presentation components:
            container.RegisterMvcControllers(app);
            container.RegisterMvcViewComponents(app);

            // Add application services. For instance:
            container.Register<IUserService, UserService>(Lifestyle.Scoped);

            // Cross-wire ASP.NET services (if any). For instance:
            container.RegisterSingleton(app.ApplicationServices.GetService());
        }

4.在Configure方法中添加这几句初始化SimpleInjector

            InitializeContainer(app);
            container.Verify();

5.使用方法

 public class HomeController : Controller
{
        public readonly IUserService _userService;
        public HomeController(IUserService userService)
        {
            _userService = userService;
        }
        public IActionResult Index()
        {
            var a = _userService.test();
       
            return View();
        }
}

SimpleInjector官方地址 :官方地址


LoneKing