纳米材料尺寸是指材料的什么尺寸在纳米量级

2360人阅读
参考资料:
1&创建Asp.net MVC项目并引入Autofac
首先,创建一个MVC站点。然后通过或到官网下载来引入类库。个人推荐前者,因为从VS2010开始,已内集可视化的NuGet功能,使用起来非常方便。如下图所示:
如果是web项目就下载这个AutoFac & 如果是MCV项目则下载&AutoFac asp.net mvc
因为我们这里是MVC项目,所有不需要下这个Autofac 。而是需要下载下面那副图的
AutoFac asp.net mvc 5 Integration
如果是MC项目 这需要下的这个专用于MVC的 AutoFac asp.net mvc
这下我们在MVC项目的引用中查看System.Web.Mvc 然后点击属性 我们看到MVC从4.0版本升级到5.2.3版本了
& & & & &&
Global.asax
using Autofac.Integration.M
using System.Collections.G
using System.L
using System.R
using System.W
using System.Web.M
using System.Web.O
using System.Web.R
namespace CMS.MvcUI
public class MvcApplication : System.Web.HttpApplication
protected void Application_Start()
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
BuiderIocContainer();
public static void BuiderIocContainer()
var builder = new ContainerBuilder();
builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());//注册mvc容器的实现
//如果有web类型,请使用如下获取Assenbly方法(获取所有需要用到的程序集,放到list中)
//用GetReferencedAssemblies方法获取当前应用程序下所有的程序集
var assemblys = BuildManager.GetReferencedAssemblies().Cast&Assembly&().ToList();
builder.RegisterAssemblyTypes(assemblys.ToArray())//查找程序集中以Repository结尾的类型
.Where(t =& t.Name.EndsWith(&Bll&))//查找所有程序集下面以Bll结尾的类
.AsImplementedInterfaces(); //将找到的类和对应的接口放入IOC容器(放到IOC容器中有什么用处?:)
builder.RegisterAssemblyTypes(assemblys.ToArray())//查找程序集中以Dal结尾的类型
.Where(t =& t.Name.EndsWith(&Dal&))
.AsImplementedInterfaces();//表示注册的类型,以接口的方式注册
//builder.RegisterAssemblyTypes(assemblys.ToArray()).AsImplementedInterfaces(); //这样写就将应用程序下所有的类都注册了
//RegisterType表示我要注册什么类型; As&T_UserInfoBll&表示这个类型需要实现什么接口。IT_UserInfoBll就是接口名称
//builder.RegisterType&T_UserInfoBll&().As&IT_UserInfoBll&();
// builder.RegisterType&GmsWorkContext&();
// builder.RegisterType&GmsWorkContext&().PropertiesAutowired();
// builder.RegisterType&UserService&().As&IUserService&();
// builder.RegisterType&EasyAuthorize&().PropertiesAutowired();
var container = builder.Build(); //Build()方法是表示:创建一个容器
//config.DependencyResolver = new AutofacDependencyResolver(container);//注册api容器需要使用HttpConfiguration对象
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//注册MVC容器
Home控制器
using CMS.IDAL;
using CMS.M
using System.Collections.G
using System.L
using System.W
using System.Web.M
namespace CMS.MvcUI.Controllers
using IBLL;
public class HomeController : Controller
IT_UserInfoBll _
public HomeController(IT_UserInfoBll
bll) //使用构造函数实现注入
public ActionResult Index()
return View();
BaseBll.cs
using System.Collections.G
using System.L
using System.T
using System.Threading.T
namespace CMS.BLL
using IBLL;
using IDAL;
using System.Linq.E
public class BaseBll&TEntity&:IBaseBll&TEntity& where TEntity:class
protected IBaseDal&TEntity& _
//public BaseBll(IBaseDal&TEntity& ibasedal)
_ibasedal =
public List&TEntity& QueryWhere(Expression&Func&TEntity, bool&& where)
return _ibasedal.QueryWhere(where);
T_UserInfoBll.cs
using System.Collections.G
using System.L
using System.T
using System.Threading.T
namespace CMS.BLL
using IBLL;
using IDAL;
public class T_UserInfoBll : BaseBll&T_UserInfo&, IT_UserInfoBll
public IT_UserInfoDal _
public T_UserInfoBll(IT_UserInfoDal dal)
base._ibasedal =
BaseDal.cs
using System.Collections.G
using System.L
using System.T
using System.Threading.T
namespace CMS.DAL
using IDAL;
using System.Linq.E
public class BaseDal&TEntity&:IBaseDal&TEntity& where TEntity:class
BaseDbContext db = new BaseDbContext();
public List&TEntity& QueryWhere(Expression&Func&TEntity, bool&& where)
return db.Set&TEntity&().Where(where).ToList();
T_UserInfoDal.cs
using System.Collections.G
using System.L
using System.T
using System.Threading.T
namespace CMS.DAL
using IDAL;
public class T_UserInfoDal:BaseDal&T_UserInfo&,IT_UserInfoDal
BaseDbContext.cs
using System.Collections.G
using System.L
using System.T
using System.Threading.T
namespace CMS.DAL
using System.Data.E
public class BaseDbContext:DbContext
public BaseDbContext()
: base(&salesEntities&)



参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:438079次
积分:8790
积分:8790
排名:第1840名
原创:449篇
转载:23篇
评论:51条
(4)(2)(2)(4)(6)(1)(2)(3)(8)(4)(8)(12)(8)(6)(5)(19)(10)(11)(5)(19)(7)(12)(29)(7)(2)(19)(12)(12)(9)(26)(23)(32)(6)(14)(23)(15)(21)(1)(5)(13)(13)(15)(16)Spring依赖注入,属性注入和构造函数注入 - 为程序员服务
为程序员服务
Spring依赖注入,属性注入和构造函数注入
Spring是一个java框架,依赖注入是指类实例不是通过调用类的构造函数来实现,而是通过xml或者注解注入来自动生成类的实例,这样做可以将类和类之间直接通过构造函数来相互依赖改进为通过配置文件或者注解来依赖,从而使类和类不必通过构造函数直接耦合,增加程序的灵活性。
下面我们通过实战看下如何使用spring的依赖注入,建议使用spring提供的开发工具sts。
首先新建一个maven项目,在引入spring相关的maven依赖项,在pom.xml中添加如下依赖:
&dependency&
&groupId&org.springframework&/groupId&
&artifactId&spring-context&/artifactId&
&version&3.0.0.RC2&/version&
&/dependency&
然后,需要在项目中添加source folder,src/main/resources,然后在此文件夹下新建一个xml文件,命名为spring.xml
在spring文件中添加下面内容:
&?xml version=&1.0& encoding=&utf-8&?&
&beans xmlns=&http://www.springframework.org/schema/beans&
xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xmlns:context=&http://www.springframework.org/schema/context&
xsi:schemaLocation=&http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd&&
这样我们的准备工作就做完了,我们添加了spring的依赖jar包,并且在资源文件路径下添加了spring.xml来做依赖注入的配置文件。下面看下我们这个demo要做什么。
假定我们要定制一辆车Car,我们需要一个People来驾驶这辆车。
首先我们定义Car类,假定Car类有两个属性品牌brand和颜色color。
package cn.outofmemory.
public class Car {
public Car() {
public Car(String brand, String color) {
this.color =
this.brand =
* @return the brand
public String getBrand() {
* @param brand the brand to set
public void setBrand(String brand) {
this.brand =
* @return the color
public String getColor() {
* @param color the color to set
public void setColor(String color) {
this.color =
我们再看下People类,假定他有一个属性是自己拥有的car,和一个方法drive()驾驶拥有的car。
package cn.outofmemory.
public class People {
private Car myC
* @return the myCar
public Car getMyCar() {
return myC
* @param myCar the myCar to set
public void setMyCar(Car myCar) {
this.myCar = myC
public void drive() {
String drivingMessage = String.format(&I am driving, my car's %s, its color is %s&,
this.getMyCar().getBrand(),
this.getMyCar().getColor());
System.out.println(drivingMessage);
为了可以通过配置让不同的People可以驾驶不同的Car,我们需要定义spring.xml配置文件:
首先我们定义两辆车,一辆是红色的宝马,另一个是白色的奔驰。
在spring.xml的根节点beans中添加如下定义:
&bean id=&carA& class=&cn.outofmemory.hellospring.Car&&
&property name=&brand& value=&宝马&/&
&property name=&color& value=&红色&/&
&bean id=&carB& class=&cn.outofmemory.hellospring.Car&&
&constructor-arg name=&brand& value=&奔驰&/&
&constructor-arg name=&color& value=&白色&/&
可以看到carA是通过属性输入,而carB是通过构造函数注入的,下面我们在定义一个People 的bean。
&bean class=&cn.outofmemory.hellospring.People&&
&property name=&myCar& ref=&carA&/&
People是通过属性注入的,还有一点是People的这个bean未指定id属性,只是指定了class属性,也就是说我们不能通过名称来获得people类的实例,而只能通过class来获得。
上述配置文件中定义了需要的类,下面我们来使用这些类和bean,我们需要在App.java中使用定义的spring配置文件,并让people drive()
package cn.outofmemory.
import org.springframework.context.ApplicationC
import org.springframework.context.support.ClassPathXmlApplicationC
* Hello world!
public class App
public static void main( String[] args )
ApplicationContext appContext = new ClassPathXmlApplicationContext(&/spring.xml&);
People commonPeople = appContext.getBean(People.class);
commonPeople.drive();
在App.java的main方法中首先声明了appContext,这个appContext读取了上面的配置文件spring.xml,然后我们声明commonPeople实例,并调用其drive方法。
运行App,会得到如下输出:
17:11:12 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@133f1d7: startup date [Fri Jun 14 17:11:12 CST 2013]; root of context hierarchy
17:11:12 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring.xml]
17:11:12 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@b61fd1: defining beans [carA,carB,cn.outofmemory.hellospring.People#0]; root of factory hierarchy
I am driving, my car's 宝马, its color is 红色
最下面的一行是我们的输出信息,而上面的信息是spring框架打印出来的信息。
上述是个spring的简单的注入入门实例,我们再看一个稍稍复杂一点的,上面的people是一个普通人,我们再来定义一个高富帅,高富帅与普通人的区别在于它有很多车,而在每次驾驶之前都要随机选一辆车来驾驶。
我们需要一个新的People类,TallRichHansom,根据上述特点,他的类定义如下:
package cn.outofmemory.
import java.util.L
import java.util.R
public class TallRichHansom extends People {
private List&Car&
* @return the cars
public List&Car& getCars() {
* @param cars the cars to set
public void setCars(List&Car& cars) {
this.cars =
public void drive() {
int carCount = this.getCars().size();
int choiseIndex = new Random().nextInt(carCount);
Car choise = this.getCars().get(choiseIndex);
this.setMyCar(choise);
super.drive();
我们给高富帅添加了cars属性,并重写了其drive方法,在每次drive之前都做一下随机选车。
下面我们给高富帅配置spring文件,在spring.xml中添加下面bean定义,我们给高富帅设置了cars属性,这个属性是一个list,需要在property节点中首先添加list节点,然后添加一个一个的car节点:
&bean class=&cn.outofmemory.hellospring.TallRichHansom&&
&property name=&cars&&
&ref bean=&carA&/&
&ref bean=&carB&/&
&bean class=&cn.outofmemory.hellospring.Car&&
&property name=&brand& value=&法拉利&/&
&property name=&color& value=&黑色& /&
&/property&
然后我们在App.java中让高富帅驾驶自己的车三次。
package cn.outofmemory.
import org.springframework.context.ApplicationC
import org.springframework.context.support.ClassPathXmlApplicationC
* Hello world!
public class App
public static void main( String[] args )
ApplicationContext appContext = new ClassPathXmlApplicationContext(&/spring.xml&);
People trh = appContext.getBean(TallRichHansom.class);
trh.drive();
trh.drive();
trh.drive();
输出高富帅驾车的结果是随机显示的,如果高富帅那天心血来潮想买新车的话,我们没有必要修改java代码,只需要在spring.xml中给他添加新车的配置就可以了。
您可能的代码
相关聚客文章
荣誉:1346
相关专栏文章解读ASP.NET 五 & MVC6系列(7):依赖注入 - ASP当前位置:& &&&解读ASP.NET 五 & MVC6系列(7):依赖注入解读ASP.NET 五 & MVC6系列(7):依赖注入&&网友分享于:&&浏览:0次解读ASP.NET 5 & MVC6系列(7):依赖注入在前面的章节(Middleware章节)中,我们提到了依赖注入功能(Dependency Injection),ASP.NET 5正式将依赖注入进行了全功能的实现,以便开发人员能够开发更具弹性的组件程序,MVC6也利用了依赖注入的功能重新对Controller和View的服务注入功能进行了重新设计;未来的依赖注入功能还可能提供更多的API,所有如果还没有开始接触依赖注入的话,就得好好学一下了。
在之前版本的依赖注入功能里,依赖注入的入口有MVC中的IControllerFactory和Web API中的IHttpControllerActivator中,在新版ASP.NET5中,依赖注入变成了最底层的基础支撑,MVC、Routing、SignalR、Entity Framrwork等都依赖于依赖注入的IServiceProvider接口,针对该接口微软给出了默认的实现ServiceProvider,以及Ninject和AutoFac版本的包装,当然你也可以使用其它第三方的依赖注入容器,如Castle Windsor等;一旦应用了第三方容器,所有的依赖解析都会被路由到该第三方容器上。
针对通用的依赖类型的解析与创建,微软默认定义了4种类别的生命周期,分别如下:
任何时间都只能使用特定的实例对象,开发人员需要负责该对象的初始化工作。
每次都重新创建一个实例。
创建一个单例,以后每次调用的时候都返回该单例对象。
在当前作用域内,不管调用多少次,都是一个实例,换了作用域就会再次创建实例,类似于特定作用内的单例。
类型注册与示例
依赖注入类型的注册一般是在程序启动的入口中,如Startup.cs中的ConfigureServices中,该类的主要目的就是注册依赖注入的类型。由于依赖注入的主要体现是接口编程,所以本例中,我以接口和实现类的方式来举例。
首先声明一个接口ITodoRepository和实现类TodoRepository1,代码如下:
public interface ITodoRepository
IEnumerable&TodoItem& AllItems { }
void Add(TodoItem item);
TodoItem GetById(int id);
bool TryDelete(int id);
public class TodoItem
public int Id { }
public string Name { }
public class TodoRepository : ITodoRepository
readonly List&TodoItem& _items = new List&TodoItem&();
public IEnumerable&TodoItem& AllItems
get { return _ }
public TodoItem GetById(int id)
return _items.FirstOrDefault(x =& x.Id == id);
public void Add(TodoItem item)
item.Id = 1 + _items.Max(x =& (int?)x.Id) ?? 0;
_items.Add(item);
public bool TryDelete(int id)
var item = GetById(id);
if (item == null) { }
_items.Remove(item);
为了演示不同的声明周期类型,建议多实现几个类,比如TodoRepository2、TodoRepository3、TodoRepository4等,以便进行演示。
然后在ConfigureServices方法内注册接口ITodoRepository类型和对应的实现类,本例中根据不同的生命周期注册了不同的实现类,具体示例如下:
//注册单例模式,整个应用程序周期内ITodoRepository接口的示例都是TodoRepository1的一个单例实例
services.AddSingleton&ITodoRepository, TodoRepository1&();
services.AddSingleton(typeof(ITodoRepository), typeof(TodoRepository1));
// 等价形式
//注册特定实例模型,整个应用程序周期内ITodoRepository接口的示例都是固定初始化好的一个单例实例
TodoRepository2
services.AddInstance&ITodoRepository&(new TodoRepository2());
services.AddInstance(typeof(ITodoRepository), new TodoRepository2());
// 等价形式
//注册作用域型的类型,在特定作用域内ITodoRepository的示例是TodoRepository3
services.AddScoped&ITodoRepository, TodoRepository3&();
services.AddScoped(typeof(ITodoRepository), typeof(TodoRepository3));// 等价形式
//获取该ITodoRepository实例时,每次都要实例化一次TodoRepository4类
services.AddTransient&ITodoRepository, TodoRepository4&();
services.AddTransient(typeof(ITodoRepository), typeof(TodoRepository));// 等价形式
//如果要注入的类没有接口,那你可以直接注入自身类型,比如:
services.AddTransient&LoggingHelper&();
依赖注入的在MVC中的使用方式目前有三种,分别是Controller的构造函数、属性以及View中的Inject形式。其中构造函数注入和之前的MVC中的是一样的,示例代码如下:
public class TodoController : Controller
private readonly ITodoRepository _
/// 依赖注入框架会自动找到ITodoRepository实现类的示例,赋值给该构造函数
public TodoController(ITodoRepository repository)
_repository =
public IEnumerable&TodoItem& GetAll()
return _repository.AllI
//这里就可以使用该对象了
属性注入,则是通过在属性上加一个[Activate]属性即可实现自动获取实例。
public class TodoController : Controller
// 依赖注入框架会自动找到ITodoRepository实现类的示例,赋值给该属性
[Activate]
public ITodoRepository Repository { }
public IEnumerable&TodoItem& GetAll()
return Repository.AllI
注意:这种方式,目前只适用于Controller以及子类,不适用于普通类同时:通过这种方式,你可以获取到更多的系统实例对象,如ActionContext、HttpContext、HttpRequest、HttpResponse、 ViewDataDictionary、以及ActionBindingContext。
在视图中,则可以通过@inject关键字来实现注入类型的实例提取,示例如下:
@using WebApplication1
@inject ITodoRepository repository
@repository.AllItems.Count()
而最一般的使用方式,则是获取IServiceProvider的实例,获取该IServiceProvider实例的方式目前有如下几种(但范围不同):
var provider1 = this.Request.HttpContext.ApplicationS 当前应用程序里注册的Service
var provider2 = Context.RequestS
// Controller中,当前请求作用域内注册的Service
var provider3 = R //Controller中
然后通过GetService和GetRequiredService方法来获取指定类型的实例,示例如下:
var _repository1 = provider1.GetService(typeof(ITodoRepository));
var _repository2 = provider1.GetService&LoggingHelper&();//等价形式
//上述2个对象可能为空
var _repository3 = provider1.GetRequiredService(typeof(ITodoRepository));
var _repository4 = provider1.GetRequiredService&LoggingHelper&();//等价形式
//上述2个对象肯定不为空,因为如果为空的话,会自动抛异常出来
普通类的依赖注入
在新版的ASP.NET5中,不仅支持上面我们所说的接口类的依赖注入,还支持普通的类型的依赖注入,比如我们生命一个普通类,示例如下:
public class AppSettings
public string SiteTitle { }
上述普通类要保证有无参数构造函数,那么注册的用法,就应该像如下这样:
services.Configure&AppSettings&(app =&
app.SiteTitle = &111&;
使用的时候,则需要获取IOptions&AppSettings&类型的实例,然后其Options属性即是AppSettings的实例,代码如下:
var appSettings = app.ApplicationServices.GetRequiredService&IOptions&AppSettings&&().O
当然,我们也可以在视图中,使用@inject语法来获取实例,示例代码如下:
@inject IOptions&AppSettings& AppSettings
&title&@AppSettings.Options.SiteTitle&/title&
基于Scope生命周期的依赖注入
普通的Scope依赖注入
基于Scope作用域的实例在创建的时候需要先创建作用域,然后在该作用域内再获取特定的实例,我们看看一个示例并对其进行验证。首先,注册依赖注入类型,代码如下:
services.AddScoped&ITodoRepository, TodoRepository&();
然后创建作用域,并在该作用域内获取实例:
var serviceProvider = R
var scopeFactory = serviceProvider.GetService&IServiceScopeFactory&(); //获取Scope工厂类
using (var scope = scopeFactory.CreateScope())
// 创建一个Scope作用域
var containerScopedService = serviceProvider.GetService&ITodoRepository&();
//获取普通的实例
var scopedService1 = scope.ServiceProvider.GetService&ITodoRepository&(); //获取当前Scope的实例
Thread.Sleep(200);
var scopedService2 = scope.ServiceProvider.GetService&ITodoRepository&(); //获取当前Scope的实例
Console.WriteLine(containerScopedService == scopedService1); // 输出:False
Console.WriteLine(scopedService1 == scopedService2); //输出:True
另外,Scope也可以进行嵌套,嵌套的内外作用域所获取的实例也是不相同的,实例代码如下:
var serviceProvider = R
var outerScopeFactory = serviceProvider.GetService&IServiceScopeFactory&();
using (var outerScope = outerScopeFactory.CreateScope()) //外部Scope作用域
var innerScopeFactory = outerScope.ServiceProvider.GetService&IServiceScopeFactory&();
using (var innerScope = innerScopeFactory.CreateScope()) //内部Scope作用域
var outerScopedService = outerScope.ServiceProvider.GetService&ITodoRepository&();
var innerScopedService = innerScope.ServiceProvider.GetService&ITodoRepository&();
Console.WriteLine(outerScopedService == innerScopedService); // 输出:False
基于HTTP请求的Scope依赖注入
在之前很多流行的DI容器中,针对每个请求,在该请求作用域内保留一个单实例对象是很流行的,也就是在每次请求期间一个类型的对象实例只会创建一次,这样可以大大提高性能。
在ASP.NET5中,基于HTTP请求的Scope依赖注入是通过一个ContainerMiddleware来实现的,调用该Middleware时,会创建一个限定作用域的DI容器,用于替换当前请求中已有的默认DI容器。在该管线中,所有后续的Middleware都会使用这个新的DI容器,在请求走完整个Pipeline管线以后,该ContainerMiddleware的作用就结束了,此时作用域会被销毁,并且在该作用域内创建的实例对象也都会销毁释放。
ContainerMiddleware的时序图如下所示:
具体的使用方式如下:
app.Use(new Func&RequestDelegate, RequestDelegate&(nextApp =& new ContainerMiddleware(nextApp, app.ApplicationServices).Invoke));
普通类的依赖注入处理
目前普通类的依赖注入,只支持构造函数,比如我们定于一个TestService类,代码如下:
public class TestService
private ITodoRepository _
public TestService(ITodoRepository r)
_repository =
public void Show()
Console.WriteLine(_repository.AllItems);
通过在构造函数里传入ITodoRepository类的参数来使用该实例,使用的时候需要先将该类注册到DI容器中,代码如下:
services.AddScoped&ITodoRepository, TodoRepository&();
services.AddSingleton&TestService&();
然后调用如下语句即可使用:
var service = serviceProvider.GetRequiredService&TestService&();
另外,需要注意,在目前的情况下,不能使用[Activate]来使用依赖注入功能,比如,如下代码在获取TestService2实例的过程中会出现错误:
public class TestService2
[Activate]
public ITodoRepository Repository { }
public void Show()
Console.WriteLine(Repository.AllItems);
普通类中获取HttpContext实例
在MVC6中,我们没办法通过HttpContent.Current来获取上下文对象了,所以在普通类中使用的时候就会出问题,要想在普通类中使用该上下文对象,需要通过依赖注入来获取HttpContext实例,微软在ASP.NET5中,提供了IHttpContextAccessor接口用于获取该上下文对象。也就是说,我们可以将该类型的参数放在构造函数中,以获取上下文实例,代码如下:
public class TestService3
private IHttpContextAccessor _httpContextA
public TestService3(IHttpContextAccessor httpContextAccessor)
_httpContextAccessor = httpContextA
public void Show()
var httpContext = _httpContextAccessor.V//获取上下文对象实例
Console.WriteLine(httpContext.Request.Host.Value);
而使用的时候,则直接通过如下语句就可以了,代码如下:
var service = serviceProvider.GetRequiredService&TestService3&();
service.Show();
提示:普通类的构造函数中,可以传入多个DI容器支持的数据类似作为参数。
使用第三方DI容器
目前,.NETCore不支持,只能在全功能版的.NET framework上才能使用,所以使用的时候需要注意一下。第三方DI容器的替换通常是在Startup.cs的Configure方法中进行的,在方法的开始处进行替换,以便后续的Middleware会使用相关的依赖注入功能。
首先要引入第三方的容器,以Autofac为例,引入Microsoft.Framework.DependencyInjection.Autofac,然后加入如下示例中的替换代码即可:
app.UseServices(services =&
services.AddMvc();// AddMvc要在这里注册
var builder = new ContainerBuilder();// 构造容器构建类
builder.Populate(services);//将现有的Services路由到Autofac的管理集合中
IContainer container = builder.Build();
return container.Resolve&IServiceProvider&();//返回AutoFac实现的IServiceProvider
注意,使用上述方法的时候,要把Mvc的注册代码services.AddMvc();必须要从ConfigureServices中挪到该表达式内,否则会报异常,等待微软解决。
另外,还有一个方式,微软目前的实例项目中还没有公开,通过分析一些代码,我们可以发现,在Microsoft.AspNet.Hosting程序中的StartupLoader.cs负责程序入口点的执行,在该文件中,我们知道首先是调用Startup.cs中的ConfigureServices方法,然后再调用Configure方法;我们可以看到示例中的ConfigureServices的返回值是void类型的,但在源码分析中发现,在根据约定解析ConfigureServices方法的时候,其首先判断有没有返回类型是IServiceProvider的,如果有则执行该方法,用使用该返回中返回的新IServiceProvider实例;没有的话,再继续查找void类型的ConfigureServices方法。所以,我们可以通过这种方式,来替换第三方的DI容器,实例代码如下:
// 需要先删除void类型的ConfigureServices方法
public IServiceProvider ConfigureServices(IServiceCollection services)
var builder = new ContainerBuilder();
// 构造容器构建类
builder.Populate(services);
//将现有的Services路由到Autofac的管理集合中
IContainer container = builder.Build();
return container.Resolve&IServiceProvider&(); //返回AutoFac实现的IServiceProvider
这样,你就可以像以往一样,使用Autofac的方式进行依赖类型的管理了,示例如下:
public class AutofacModule : Module
protected override void Load(ContainerBuilder builder)
builder.Register(c =& new Logger())
.As&ILogger&()
.InstancePerLifetimeScope();
builder.Register(c =& new ValuesService(c.Resolve&ILogger&()))
.As&IValuesService&()
.InstancePerLifetimeScope();
地址:另外一个关于Autofac集成的案例:
在使用依赖注入的的时候,我们应该遵守如下最佳实践。
做任何事情之前,务必在程序入口点提前注册所有的依赖类型。
避免直接使用IServiceProvider接口,相反,在构造函数里显式添加需要依赖的类型即可,让依赖注入引擎自己来解析实例,一旦依赖很难管理的话,就使用抽象工厂。
基于接口进行编程,而不是基于实现进行编程。
参考1:参考2:
同步与推荐
本文已同步至目录索引:
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 1234567891011 Copyright & &&版权所有

我要回帖

更多关于 纳米材料的小尺寸效应 的文章

 

随机推荐