Core篇——初探依赖注入
目录
1、DI&&IOC简单介绍
2、UML类图中六种关联关系
3、.net core 中DI的使用
4、.net core DI初始化源码初窥
DI&&IOC简单介绍
DI(依赖注入)是实现IOC(控制反转)的一种方式。面向对象设计六大基本原则的依赖倒置原则,高层类不应该依赖于低层类的实现 ,而应该依赖于它的抽象。所以我们现在工作中,经常是构造函数中,注入需要实现的类的接口;IOC描述的是当一个类需要另外一个类时,这个类的实现不应该由它来决定,实现由一个DI容器来实现,并将其注入到这个类中。
UML类图中六种关联关系
顺便复习一波UML类图中的六种关系:
.net core 中DI的使用
.NET Core框架中,默认存在一个DI容器,使用的时候我们只需要将需要将接口服务放入DI容器。 这里,我们创建一个Movie类,引用efcore 添加一个数据库链接上下文。添加一个IMovieService 接口和MovieService 类。代码如下所示
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
:base(options)
{ }
public DbSet<Movie> Movie { get; set; } }
数据库链接上下文
public class Startup
{
public IConfiguration Configuration { get; set; } public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json"); //将appsettings 配置文件读入系统配置 Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("MVCMovieContext")); //添加数据库链接字符串
});
services.AddRouting();
services.AddMvc();
services.AddScoped<IMovieService, MovieService>();//接口服务放入DI容器
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Startup类
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
Movie类
public interface IMovieService
{
Movie GetMovie(int Id);
}
public class MovieService : IMovieService
{
private readonly ApplicationDbContext _applicationDbContext; public MovieService(ApplicationDbContext applicationDbContext)
{
_applicationDbContext = applicationDbContext;
}
public Movie GetMovie(int Id)
{
var entity = _applicationDbContext.Movie.FirstOrDefault(t => t.ID == Id);
if (entity == null)
return null;
return entity;
}
}
接口以及服务
public class HomeController : Controller
{
private readonly IMovieService _movieService;
public HomeController(IMovieService movieService)
{
_movieService = movieService;
}
public IActionResult Index(int Id)
{
var movie = _movieService.GetMovie(Id);
return View(movie);
}
}
Home控制器代码
这里我们在MovieService中,注入了数据库链接上下文实例;在HomeController 中,注入了IMovieService 。
.net core DI初始化源码初窥
在 .Net Core 框架的Main函数中,
1、WebHost 通过CreateDefaultBuilder 创建一个WebHostBuilder实例。WebHostBuilder调用 Build方法,在Build方法中,调用BuildCommonServices方法返回一个IServiceCollection。这个ServiceCollection是在BuildCommonServices方法中,实例化的一个,然后在实例化的ServiceCollection中加入一些默认的配置(例如HttpContextFactory,IHostingEnvironment)。
拿到IServiceCollection对象后,在Build方法中,对IServiceCollection IServiceCollection和IServiceCollection.ServiceProvider 进行一个初始化操作(Initialize)方法,然后返回WebHost。
2、在Initialize方法中,执行EnsureApplicationServices方法,EnsureApplicationServices中又通过调用EnsureStartup方法,在EnsureStartup中,通过WebHostProvider拿到StartUp实例。EnsureApplicationServices拿到StartUp后调用ConfigureServices方法,参数是ServiceCollection来完成DI。(这也就是我们新建一个项目StartUp 中的ConfigureServices方法,然后各种services.addxxxx(),把接口和服务放入到IserviceCollection)
Jesse博客学习笔记。传送门=》 http://video.jessetalk.cn/
最新文章
- jquery插件jquery.LightBox.js之点击放大图片并左右点击切换图片(仿相册插件)
- 带缓存的输入输出-bufferedinputstream类与bufferedoutputstream类
- SSDT Hook实现简单的进程隐藏和保护【转载】
- [安卓]我的安卓开发FAQ
- semanage: 未找到命令
- hdu 4003 Find Metal Mineral 树形DP
- 团体程序设计天梯赛-练习集L1-012. 计算指数
- HDU 1004 ballons(map)
- 中文翻译:pjsip教程(二)之ICE穿越打洞:Interactive Connectivity Establishment简介
- 本地通过Eclipse链接Hadoop操作Mysql数据库问题小结
- loadrunner使用socket协议来实现客户端对服务器产生压力实例。(通过发送心跳包,达到连接多个客户端的目的)
- 采用集成的Windows验证和使用Sql Server身份验证进行数据库的登录
- 描述性统计指标 - 众数 Mode
- 转:jsp与servlet的区别与联系
- Dynamics 365创建用户提示:您正在尝试使用已由其他用户使用的域登录来创建用户。如何解决。
- js面向对象实例
- vue-循环标记列表元素
- 关系型数据库 和 非关系型数据对比 以及 MySQL与Oracle对比
- cxgrid中,如何根据列名或字段名取得footer值
- MySQL性能优化(三)-- 索引