在工作开发中很多地方都会使用到接口模式开发,这里就会用到依赖注入,.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 到此完美结束!

最新文章

  1. 配置nginx+php
  2. Ruby--学习记录(实时更新)
  3. [Unity3D入门]分享一个自制的入门级游戏项目&quot;坦克狙击手&quot;
  4. express-3 最佳实践
  5. 深入理解MySQL开发性能优化.pptx
  6. 黄聪:MYSQL提交一批ID,查询数据库中不存在的ID并返回
  7. bzoj 2134 单选错位(期望)
  8. null和空 not null
  9. Web Services的相关名词解释:WSDL与SOAP
  10. Mysql update error: Error Code: 1175. You are using safe update mode and you tried to update a table
  11. PHP MySQL 读取数据
  12. COJ 0986 WZJ的数据结构(负十四) 区间动态k大
  13. Zend_Db_Table::getDefaultAdapter is not working
  14. IntelliJ IDEA 报错:Error:java: 未结束的字符串文字
  15. iOS----------YYModel
  16. CRT乱码问题
  17. python图片和分形树
  18. CentOS下安装Hbase
  19. Oracle数据库11gR2的卸载 - deinstall
  20. 【转】淘宝技术牛p博客整理

热门文章

  1. 第12组 Beta冲刺(4/5)
  2. [USACO5.1]二维凸包模板
  3. httpd.exe你的电脑中缺失msvcr110.dll怎么办(WIN2008服务器环境装WAMP2.5出现的问题)
  4. 刷题记录:[CISCN2019 总决赛 Day1 Web4]Laravel1
  5. [Beta]第一次 Scrum Meeting
  6. SQL多个逗号分开的字段值 取对应的数据名称信息
  7. 如何用java代码写一个堆栈
  8. IISExpress.无法启动IIS Express Web 服务器.Starting IIS Express... IIS Express is running
  9. [LeetCode] 82. Remove Duplicates from Sorted List II 移除有序链表中的重复项 II
  10. 【miscellaneous】Winserver2012安装后无法进入桌面