标签:inf start 自己 var get typeof art etag 生命周期
asp.net mvc core 内置了 IOC 容器,不再需要 autofac 等,当然 autofac 也是支持.net core
的(http://www.open-open.com/lib/view/open1454127071933.html)。内置 IOC 是通过构
造函数注入,而不是属性注入.
内置的 IOC 有三种生命周期:
Transient: Transient 服务在每次被请求时都会被创建。这种生命周期比较适用于轻量级的
无状态服务。
Scoped: Scoped 生命周期的服务是每次 web 请求被创建。
Singleton: Singleton 生命能够周期服务在第一被请求时创建,在后续的每个请求都会使用
同一个实例。如果你的应用需要单例服务,推荐的做法是交给服务容器来负责单例的创建和
生命周期管理,而不是自己来走这些事情。
public   interface IUserService
    {
        string GetStr();
    }
 public class UserService : IUserService
    {
        public string GetStr()
        {
            return "hello";
        }
    }
加入我们要以Singleton的方式让IOC容器替我们创建UserService对象,则我们只需要在Startup类的ConfigureServices方法里面调用services.AddSingleton方法
   public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton(typeof(IUserService), typeof(UserService));//最好 services.AddSingleton(typeof(IMyService),typeof(MyService));
因为这样的话可以在 MyService 中通过构造函数注入其他服务
        }
这样以后,Controller里我们使用UserService这个类的时候,就不需要自己New创建,而是需要的时候有IOC容器帮我们创建。
  public class HomeController : Controller
    {
        private IUserService userService;
        public HomeController(IUserService _userService)
        {
            userService = _userService;
        }
        public IActionResult Index()
        {
            string connStr = userService.GetStr();
            //return View();
            return Content(connStr);
        }
    }
实际项目中,我们会写许多的接口,这个时候可以通过放射的方式注入服务接口
var serviceAsm = Assembly.Load(new AssemblyName("CoreProj.Service"));
foreach(Type serviceType in serviceAsm.GetTypes()
.Where(t=>typeof(IServiceTag).IsAssignableFrom(t)&&!t.GetTypeInfo().IsAbstract))
{
var interfaceTypes = serviceType.GetInterfaces();
foreach(var interfaceType in interfaceTypes)
{
services.AddSingleton(interfaceType, serviceType);
}
}
标签:inf start 自己 var get typeof art etag 生命周期
原文地址:http://www.cnblogs.com/lyfingchow/p/7536964.html