Autofac在.NetCore 下的使用
2024-10-21 17:32:34
在工作开发中很多地方都会使用到接口模式开发,这里就会用到依赖注入,.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 到此完美结束!
最新文章
- 配置nginx+php
- Ruby--学习记录(实时更新)
- [Unity3D入门]分享一个自制的入门级游戏项目";坦克狙击手";
- express-3 最佳实践
- 深入理解MySQL开发性能优化.pptx
- 黄聪:MYSQL提交一批ID,查询数据库中不存在的ID并返回
- bzoj 2134 单选错位(期望)
- null和空 not null
- Web Services的相关名词解释:WSDL与SOAP
- Mysql update error: Error Code: 1175. You are using safe update mode and you tried to update a table
- PHP MySQL 读取数据
- COJ 0986 WZJ的数据结构(负十四) 区间动态k大
- Zend_Db_Table::getDefaultAdapter is not working
- IntelliJ IDEA 报错:Error:java: 未结束的字符串文字
- iOS----------YYModel
- CRT乱码问题
- python图片和分形树
- CentOS下安装Hbase
- Oracle数据库11gR2的卸载 - deinstall
- 【转】淘宝技术牛p博客整理
热门文章
- 第12组 Beta冲刺(4/5)
- [USACO5.1]二维凸包模板
- httpd.exe你的电脑中缺失msvcr110.dll怎么办(WIN2008服务器环境装WAMP2.5出现的问题)
- 刷题记录:[CISCN2019 总决赛 Day1 Web4]Laravel1
- [Beta]第一次 Scrum Meeting
- SQL多个逗号分开的字段值 取对应的数据名称信息
- 如何用java代码写一个堆栈
- IISExpress.无法启动IIS Express Web 服务器.Starting IIS Express... IIS Express is running
- [LeetCode] 82. Remove Duplicates from Sorted List II 移除有序链表中的重复项 II
- 【miscellaneous】Winserver2012安装后无法进入桌面