首页新闻找找看学习计划

core 中新建的mvc程序:Startup.cs中引入了 using Microsoft.Extensions.DependencyInjection;

0
悬赏园豆:30 [待解决问题]

.net core 中新建的mvc程序:Startup.cs中引入了 using Microsoft.Extensions.DependencyInjection;  求大神讲解Startup.cs中是如何使用依赖注入的?

Startup.cs代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
 8 using Microsoft.EntityFrameworkCore;
 9 using Microsoft.Extensions.Configuration;
10 using Microsoft.Extensions.DependencyInjection;
11 using Microsoft.Extensions.Logging;
12 using YunDou.Data;
13 using YunDou.Models;
14 using YunDou.Services;
15 
16 namespace YunDou
17 {
18     public class Startup
19     {
20         public Startup(IHostingEnvironment env)
21         {
22             var builder = new ConfigurationBuilder()
23                 .SetBasePath(env.ContentRootPath)
24                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
25                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
26 
27             if (env.IsDevelopment())
28             {
29                 // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
30                 builder.AddUserSecrets();
31             }
32 
33             builder.AddEnvironmentVariables();
34             Configuration = builder.Build();
35         }
36 
37         public IConfigurationRoot Configuration { get; }
38 
39         // This method gets called by the runtime. Use this method to add services to the container.
40         public void ConfigureServices(IServiceCollection services)
41         {
42             // Add framework services.
43             services.AddDbContext<ApplicationDbContext>(options =>
44                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
45 
46             services.AddIdentity<ApplicationUser, IdentityRole>()
47                 .AddEntityFrameworkStores<ApplicationDbContext>()
48                 .AddDefaultTokenProviders();
49 
50             services.AddMvc();
51 
52             // Add application services.
53             services.AddTransient<IEmailSender, AuthMessageSender>();
54             services.AddTransient<ISmsSender, AuthMessageSender>();
55         }
56 
57         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
58         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
59         {
60             loggerFactory.AddConsole(Configuration.GetSection("Logging"));
61             loggerFactory.AddDebug();
62 
63             if (env.IsDevelopment())
64             {
65                 app.UseDeveloperExceptionPage();
66                 app.UseDatabaseErrorPage();
67                 app.UseBrowserLink();
68             }
69             else
70             {
71                 app.UseExceptionHandler("/Home/Error");
72             }
73 
74             app.UseStaticFiles();
75 
76             app.UseIdentity();
77 
78             // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
79 
80             app.UseMvc(routes =>
81             {
82                 routes.MapRoute(
83                     name: "default",
84                     template: "{controller=Home}/{action=Index}/{id?}");
85             });
86         }
87     }
88 }
小灰灰反击喜洋洋的主页 小灰灰反击喜洋洋 | 初学一级 | 园豆:59
提问于:2016-07-18 09:33
< >
分享
所有回答(2)
0

就是这个

services.AddTransient<IEmailSender, AuthMessageSender>();

services.AddTransient<ISmsSender, AuthMessageSender>();

这个就是绑定,你可以把自己的类绑定到接口上,例如

services.AddTransient<IUserRepository, UserRepository>();

services.AddSingleton<IMapper>(sp => config.CreateMapper());

//获取IUserRepository的实例

var serviceProvider = services.BuildServiceProvider();

var repository=serviceProvider.GetService<IUserRepository>()

至于有AddTransient、AddScoped、AddSingleton之间的区别,可以上网去搜。。

 

Buthcer | 园豆:238 (菜鸟二级) | 2016-07-18 17:57

我在想想吧, 不理解DI,所以也不明白你在说什么

支持(0) 反对(0) 小灰灰反击喜洋洋 | 园豆:59 (初学一级) | 2016-07-19 12:24
0

你在startup里配置好注入后,例如 services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

就可以在控制器里直接通过构造方法,将ApplicationDbContext初始化,不用你自己通过new的方式初始化ApplicationDbContext了
public class ValuesController : Controller
{
private ApplicationDbContext _context;
public ValuesController(ApplicationDbContext context)
{
_context = context;
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
//通过_context执行操作
}
}

这样的有点就是,将初始化的功能,交给架构,想用什么就注入什么,将控制权交给了高层,实现了控制反转

chesterdotchen | 园豆:542 (小虾三级) | 2018-11-23 10:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册