在工作开发中很多地方都会使用到接口模式开发,这里就会用到依赖注入,.NetCore目前是自带的 ,在 Startup.cs中的 ConfigureServices方法中增加 本篇文章仅支持 3.0版本以下core

    public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddMvc().AddWebApiConventions();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressConsumesConstraintForFormFileParameters = true;
options.SuppressInferBindingSourcesForParameters = true;
options.SuppressModelStateInvalidFilter = true;
});
services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); });//返回值小写处理
services.AddMvc(option => { option.Filters.Add(typeof(SecurityAuthorizeAttribute)); });//添加过滤器
services.AddMvc(option => { option.Filters.Add(typeof(GlobalHandlerErrorAttribute)); });//添加过滤器
services.AddSingleton<CacheHelper>();
services.AddSingleton<IQRCode, RaffQRCode>();
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
}

这样明显不够方便 Autofac就解决了这一问题,那么下面就看看Autofac在.NetCore中是如何使用的:

1、首先建立简单的一个基于接口模式的项目.NteCore Mvc模式 引用  Autofac.Extensions.DependencyInjection的引用

2、在 IRepository、IServices、Repository、Services中增加相关代码 所有接口继承自IDependency

   //IRepository
public interface IBaseRepository<T> : IDependency where T : BaseEntity
{ string GetUserName();
} //Repository
public class BaseRepository<T> : IBaseRepository<T> ,IDependency where T : BaseEntity
{
public string GetUserName()
{
return "just0ne";
}
}
//IServices
public interface IBaseServices<T> : IDependency where T : BaseEntity
{ string GetUserName();
}
//Services
public class BaseServices<T> : IBaseServices<T> , IDependency where T : BaseEntity
{
public readonly IBaseRepository<T> _baseRepository; public BaseServices(IBaseRepository<T> baseRepository)
{
_baseRepository = baseRepository;
} /// <summary>
/// 获取一个用户名
/// </summary>
/// <returns></returns>
public string GetUserName()
{
return _baseRepository.GetUserName();
}
}

3、Aufofac的加入,这边需要在项目启动Startup中调整 ConfigureServices方法。具体如下

 public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); services.AddMvc();
var builder = new ContainerBuilder();//实例化 AutoFac  容器   
var assemblys = new List<Assembly>();//Service是继承接口的实现方法类库名称
string assemblysStr = "IRepository^IServices^Repository^Services"; //程序集名称
foreach (var item in assemblysStr.Split("^"))
{
assemblys.Add(Assembly.Load(item));
}
var baseType = typeof(IDependency);//IDependency 是一个接口(所有要实现依赖注入的借口都要继承该接口)
            builder.RegisterAssemblyTypes(assemblys.ToArray())
.Where(m => baseType.IsAssignableFrom(m) && m != baseType)
.AsImplementedInterfaces().InstancePerLifetimeScope();
builder.Populate(services);
return new AutofacServiceProvider(builder.Build());//将系统自带的修改为Atuofac的 重新返回 }

控制器层的调用

调用结果:

ok 到此完美结束!

Autofac在.NetCore 下的使用的更多相关文章

  1. .NetCore 下开发独立的(RPL)含有界面的组件包 (六)实现业务功能

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  2. .NetCore 下开发独立的(RPL)含有界面的组件包 (五)授权过滤参数处理

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  3. .NetCore 下开发独立的(RPL)含有界面的组件包 (四)授权过滤

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  4. .NetCore 下开发独立的(RPL)含有界面的组件包 (三)构建界面

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  5. .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服务

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  6. .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  7. NetCore下模拟和使用Modbus工业通信协议

    Tips: 1.目前NetCore下与Modbus通信的框架主要选择了 Modbus.Net  https://github.com/parallelbgls/Modbus.Net 2.modbus是 ...

  8. .netcore下的微服务、容器、运维、自动化发布

    原文:.netcore下的微服务.容器.运维.自动化发布 微服务 1.1     基本概念 1.1.1       什么是微服务? 微服务架构是SOA思想某一种具体实现.是一种将单应用程序作为一套小型 ...

  9. QQ浏览器、搜狗浏览器等兼容模式下,Asp.NetCore下,Cookie、Session失效问题

    原文:QQ浏览器.搜狗浏览器等兼容模式下,Asp.NetCore下,Cookie.Session失效问题 这些狗日的浏览器在兼容模式下,保存Cookie会失败,是因为SameSiteMode默认为La ...

随机推荐

  1. mysql 设置字段是否可以为null

    //不允许为null alter table table1 change id id ) not null; //允许为null alter table table1 change id id ) n ...

  2. Git基本介绍(三大分区及核心内部构造)

    1. Git三大工作区(工作区.暂存区和版本库) 工作区(WORKING DIRECTORY): 直接编辑文件的地方,肉眼可见直接操作: 暂存区(STAGIN AREA):数据(快照)暂时存放的地方: ...

  3. rust数据类型

    fn main() { //char支持4个字节,支持emoji let jp = "ゆ"; let emoji = "✨"; let ch = "囧 ...

  4. Redis代码示例

    RedisTemplate 如果想要在java中使用Redis相关的数据结构,要先注入RedisTemplate. @Autowired private RedisTemplate<K,V> ...

  5. 删除N天前的log日志文件:RollingFileAppender,DailyRollingFileAppender,/etc/cron

    1. 如果您使用的是Log4j,且采用的RollingFileAppender方式, 通过设置maxBackupIndex属性来指定要保留的日志文件数的最大值可以间接实现删除N天前的日志文件. 2. ...

  6. 【转】Android ROM分析(1):刷机原理及方法

    一.刷机原理 android系统启动的时候,首先会进行一些诸如硬件自检之类的操作,这些操作完成以后(至少它应该知道当前的机器有没有电),会检查一下当前手机按键的状态(接下来就是所谓刷机模式切换了,不同 ...

  7. Android 系统属性-SystemProperties详解***

    创建与修改android属性用Systemproperties.set(name, value),获取android属性用Systemproperties.get(name),需要注意的是androi ...

  8. mysql索引原理及优化(二)

    索引原理分析:数据结构 索引是最常见的慢查询优化方式其是一种优化查询的数据结构,MySql中的索引是用B+树实现,而B+树就是一种数据结构,可以优化查询速度,可以利用索引快速查找数据,优化查询. 可以 ...

  9. gmake: Nothing to be done for `all'.

    安装gc_buffercache的时候报错: [root@~ pg_buffercache]# gmake gmake: Nothing to be done for `all'. 解决方法: > ...

  10. [转]eclipse中 properties文件编码问题

    原文地址:https://blog.csdn.net/uestcong/article/details/6635123 1. Eclipse修改设置项目中用到了配置文件,所以在Eclipse中新建.p ...