ASP.NET Core 源码阅读笔记(1) ---Microsoft.Extensions.DependencyInjection
在asp .net中使用依赖注入很简单,只需要在Startup类的ConfigureServices(IServiceCollection services)方法中,通过IServiceCollection接口注入就行。
通过接口的Add*方法进行注册,代码如下:
ASP.NET Core runtime帮忙注册如下方法
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) { services.AddEntityFrameworkSqlServer().AddDbContext<**Context>(options => options.UseSqlServer(Configuration.GetConnectionString("***"))); //services.AddAuthorization(options => { options.DefaultPolicy }); // Add framework services. services.AddOptions(); services.AddDistributedMemoryCache(); services.AddMvc(); services.AddScoped<MenuService>(); services.AddTransient<ICommon, Common>(); services.AddSingleton<IConfiguration>(Configuration); }