asp.net core 四 IOC&DI Autofac
/// <summary>
/// 动物类
/// </summary>
public interface Animal
{
string Call();
}
/// <summary>
/// 狗狗类
/// </summary>
public class Dog : Animal
{
public Dog()
{
this.Name = Guid.NewGuid().ToString();
}
public string Name { get; set; }
public string Call()
{
return this.Name;
}
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient<Animal, Dog>();
//services.AddScoped<Animal, Dog>();
//services.AddSingleton<Animal, Dog>();
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace CM.NetCoreIOC.Controllers
{
public class HomeController : Controller
{
Animal animal1;
Animal animal2;
public HomeController(Animal animal1, Animal animal2)
{
this.animal1 = animal1;
this.animal2 = animal2;
}
public string Index()
{
return $"Animal 1 Name:{animal1.Call()} Animal 2 Name:{animal2.Call()}";
}
}
}



services.AddMvc();
//services.AddTransient<Animal, Dog>();
services.AddScoped<Animal, Dog>();
//services.AddSingleton<Animal, Dog>();

services.AddMvc();
//services.AddTransient<Animal, Dog>();
//services.AddScoped<Animal, Dog>();
services.AddSingleton<Animal, Dog>();



// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = new ContainerBuilder();
builder.RegisterType(typeof(Dog)).As(typeof(Animal))
.InstancePerLifetimeScope()
.PropertiesAutowired();
builder.Populate(services);
return new AutofacServiceProvider(builder.Build());
}

// 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.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
var animal1 = ActivatorUtilities.GetServiceOrCreateInstance(app.ApplicationServices, typeof(Animal));
var animal2 = app.ApplicationServices.GetService(typeof(Animal));
}
调试看看两个对象animal1与animal2


// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = new ContainerBuilder();
builder.RegisterType(typeof(Dog)).As(typeof(Animal))
.InstancePerLifetimeScope()
.PropertiesAutowired();
builder.RegisterType(typeof(HomeController))
.InstancePerLifetimeScope()
.PropertiesAutowired();
builder.Populate(services);
return new AutofacServiceProvider(builder.Build());
}

// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
services.AddMvc();
var builder = new ContainerBuilder();
builder.RegisterType(typeof(Dog)).As(typeof(Animal))
.InstancePerLifetimeScope()
.PropertiesAutowired();
builder.RegisterType(typeof(HomeController))
.InstancePerLifetimeScope()
.PropertiesAutowired();
builder.Populate(services);
return new AutofacServiceProvider(builder.Build());
}
运行效果:

public class HomeController : Controller
{
public Animal animal1 { get; set; }
public Animal animal2 { get; set; }
//public HomeController(Animal animal1, Animal animal2)
//{
// this.animal1 = animal1;
// this.animal2 = animal2;
//}
public string Index()
{
return $"Animal 1 Name:{animal1.Call()} Animal 2 Name:{animal2.Call()}";
}
}
public static IMvcBuilder AddControllersAsServices(this IMvcBuilder builder)
{
var feature = new ControllerFeature();
builder.PartManager.PopulateFeature(feature);
foreach (var controller in feature.Controllers.Select(c => c.AsType()))
{
builder.Services.TryAddTransient(controller, controller);
}
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
return builder;
}
public object Create(ControllerContext actionContext)
{
if (actionContext == null)
{
throw new ArgumentNullException(nameof(actionContext));
}
var controllerType = actionContext.ActionDescriptor.ControllerTypeInfo.AsType();
return actionContext.HttpContext.RequestServices.GetRequiredService(controllerType);
}
asp.net core 四 IOC&DI Autofac的更多相关文章
- ASP.NET Core修改IOC为Autofac
如下是我为了了解如何更换ASP.NET Core中的IOC而查找的文章,如果大家英文OK的,可以直接前往阅读,同时也已经有简单的github例子供大家参考. 参考文章: ASP.NET Core文档: ...
- 浅谈ASP.NET Core中的DI
DI的一些事 传送门马丁大叔的文章 什么是依赖注入(DI: Dependency Injection)? 依赖注入(DI)是一种面向对象的软件设计模式,主要是帮助开发人员开发出松耦合的应用程序 ...
- ASP.Net Core 3.1 With Autofac ConfigureServices returning an System.IServiceProvider isn't supported.
ASP.Net Core 3.1 With Autofac ConfigureServices returning an System.IServiceProvider isn't supported ...
- 浅谈ASP.NET Core中IOC与DI的理解和使用
说起IOC和DI,使用过ASP.NET Core的人对这两个概念一定不陌生,早前,自己也有尝试过去了解这两个东西,但是一直觉得有点很难去理解,总觉得对其还是模糊不清,所以,趁着今天有空,就去把两个概念 ...
- Asp.net Core依赖注入(Autofac替换IOC容器)
ASP.NET Core ASP.NET Core (previously ASP.NET 5) 改变了以前依赖注入框架集成进ASP.NET的方法. 以前, 每个功能 - MVC, Web API, ...
- ASP.NET Core 依赖注入(DI)
ASP.NET Core的底层设计支持和使用依赖注入.ASP.NET Core 应用程序可以利用内置的框架服务将服务注入到启动类的方法中,并且应用程序服务也可以配置注入.由ASP.NET Core 提 ...
- ASP.NET Core依赖注入(DI)
ASP.NET Core允许我们指定注册服务的生存期.服务实例将根据指定的生存时间自动处理.因此,我们无需担心清理此依赖关系,他将由ASP.NET Core框架处理.有如下三种类型的生命周期. 关于依 ...
- ASP.NET Core 四种释放 IDisposable 对象的方法
本文翻译自<Four ways to dispose IDisposables in ASP.NET Core>,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! IDispos ...
- ASP.NET Core 四种方式绑定枚举值
前言 本节我们来讲讲在ASP.NET Core MVC又为我们提供了哪些方便,之前我们探讨过在ASP.NET MVC中下拉框绑定方式,这节我们来再来重点看看枚举绑定的方式,充分实现你所能想到的场景,满 ...
随机推荐
- 使用maven搭建hibernate的pom文件配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...
- windows上nginx的安装和配置
http://www.cnblogs.com/Li-Cheng/p/4399149.html http://www.cnblogs.com/huayangmeng/archive/2011/06/15 ...
- iOS应用如何得知用户有新拍的图片?
首先,应用要知道图片库中的新图片,最重要是要有图片库的访问权限.然后每张图片除了图片本身的构成要素(像素)外,还会保存图片的拍摄时间(时间戳),地点等相关信息.时间戳就是判断新拍照片的最主要依据.
- js鼠标滚轮事件兼容
JavaScript鼠标滚轮事件 IE6.0首先实现了鼠标的滚轮事件,其良好的交互效果得到认可,随后Opera.chrome.safari等主流浏览器都实现了该效果,不过存在着很大的兼容问题. 大多数 ...
- 接口测试执行工具Postman:模拟请求、用例执行、断言、批量运行用例、简单持续集成
一.接口测试-postman-模拟HTTP Requests 二.接口测试-postman-权限Authorization 三.接口测试-postman-断言Writting Test 四.接口测试- ...
- SQL语句学习
看似简单,但其实包含很多技巧思维 1.查询课程表中所有科目大于80的学生 select distinct name from student where name not in (select nam ...
- 【java学习笔记】正则表达式
一.正则表达式 1.预定义字符集 . 表示任意一个字符 \d 表示任意一个数字 \w 表示任意一个单词字符(只能是数字.字母.下划线) \s 表示任意一个空白字符(\t\r\n\f\x0B) \D ...
- SQL中partition关键字的使用
最近在写后台语句时候,运用到了partition这样一个关键字. 先大致说一下背景,有一种数据表,如下 现在需要取出,每一个人最近的一次打卡时间. 思路是,先把数据按照人名分组,然后在每个组里面按照时 ...
- java中servletContextListener、httpSessionListener和servletRequestListener使用整理
在java web应用中,listener监听器似乎是必不可少的,常常用来监听servletContext.httpSession.servletRequest等域对象的创建.销毁以及属性的变化等等, ...
- 通过grub-install命令把grub安装到u盘-总结
通过grub-install命令把grub安装到u盘 ①准备一个u盘,容量不限,能有1MB都足够了. ②把u盘格式化(我把u盘格式化成FAT.fat32格式了,最后证明也是成功的).③开启linux系 ...