Autofac +webapi 配置
Autofac配置
using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi; namespace WebAutoFac
{
/// <summary>
/// Autofac配置
/// </summary>
public class AutoFacBootStrapper
{
/// <summary>
/// Autofac配置
/// </summary>
public static void CoreAutoFacInit()
{
#region MVC---install-package autofac.mvc5 注意版本 //var builder = new ContainerBuilder(); //SetupResolveRules(builder); ////注册所有的Controllers
//builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
//var container = builder.Build();
//System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion #region Webapi和MVC ---install-package autofac.mvc5 install-package autofac.webapi2 注意版本 var builder = new ContainerBuilder();
SetupResolveRules(builder); //注册所有的Controllers
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
//注册所有的ApiControllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); var container = builder.Build();
//注册所有的Controllers
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
//注册api容器需要使用HttpConfiguration对象
HttpConfiguration config = GlobalConfiguration.Configuration;
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion #region 自动注入 --- 注释 ////创建autofac管理注册类的容器实例
//var builder = new ContainerBuilder();
//HttpConfiguration config = GlobalConfiguration.Configuration;
//Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
////注册所有实现了 IDependency 接口的类型
//Type baseType = typeof(IDependency);
//builder.RegisterAssemblyTypes(assemblies)
// .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
// .AsSelf().AsImplementedInterfaces()
// .PropertiesAutowired().InstancePerLifetimeScope();
////注册MVC类型
//// builder.RegisterControllers(assemblies).PropertiesAutowired();
////注册Api类型
//builder.RegisterApiControllers(assemblies).PropertiesAutowired();
////builder.RegisterFilterProvider();
//builder.RegisterWebApiFilterProvider(config);
//var container = builder.Build();
////注册api容器需要使用HttpConfiguration对象
//config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
////注册解析
//DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion //有了 IDependency 这个基接口,我们只需要 Global 中很简单的几行代码,就可以完成整个系统的依赖注入匹配
//ContainerBuilder builder = new ContainerBuilder();
//builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>));
//Type baseType = typeof(IDependency); //// 获取所有相关类库的程序集
//Assembly[] assemblies = ... //builder.RegisterAssemblyTypes(assemblies)
// .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
// .AsImplementedInterfaces().InstancePerLifetimeScope();//InstancePerLifetimeScope 保证对象生命周期基于请求
//IContainer container = builder.Build();
//DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
} private static void SetupResolveRules(ContainerBuilder builder)
{
//WebAPI只用引用services和repository的接口,不用引用实现的dll。
//如需加载实现的程序集,将dll拷贝到bin目录下即可,不用引用dll
var iServices = Assembly.Load("IBLL");
var services = Assembly.Load("BLL");
//var iRepository = Assembly.Load("WebAPI.IRepository");
//var repository = Assembly.Load("WebAPI.Repository"); //根据名称约定(服务层的接口和实现均以Services结尾),实现服务接口和服务实现的依赖
builder.RegisterAssemblyTypes(iServices, services)
.Where(t => t.Name.EndsWith("BLL"))
.AsImplementedInterfaces(); ////根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖
//builder.RegisterAssemblyTypes(iRepository, repository)
// .Where(t => t.Name.EndsWith("Repository"))
// .AsImplementedInterfaces(); //var cont = Assembly.Load("WebAutoFac");
////根据名称约定(服务层的接口和实现均以Services结尾),实现服务接口和服务实现的依赖
//builder.RegisterAssemblyTypes(cont)
// .Where(t => t.Name.EndsWith("Controller"))
// .AsImplementedInterfaces(); ////使用新的覆盖旧的注册DLL-使用UserNew代替UserOld
//builder.RegisterType<BLL.UserBLL>().As<IBLL.IUserBLL>(); }
}
}
using Autofac;
using BLL;
using IBLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http; namespace WebAutoFac.Controllers
{
/// <summary>
///
/// </summary>
[RoutePrefix("User")]
public class UserController : ApiController
{
private IUserBLL _userBll;
private IPeopleBLL _peopleBll; /// <summary>
///
/// </summary>
/// <param name="userBLL"></param>
/// <param name="peopleBll"></param>
public UserController(IUserBLL userBLL, IPeopleBLL peopleBll)
{
_userBll = userBLL;
_peopleBll = peopleBll;
}
/// <summary>
/// 最原始的方式直接new(需添加对BLL层的引用)
/// </summary>
/// <returns></returns>
[HttpGet,Route("Refernce")]
public string GetUserInfoByRefernce()
{
UserBLL userBll = new UserBLL();
var result = userBll.GetUserInfor();
return result;
} /// <summary>
/// 面向接口编程(仍需添加对BLL层的引用)
/// </summary>
/// <returns></returns>
[HttpGet, Route("Interface")]
public string GetUserInfoByInterface()
{
IUserBLL userBll = new UserBLL();
var result = userBll.GetUserInfor();
return result;
}
/// <summary>
/// 接口+反射(只需将BLL层的程序集拷贝进来)
/// </summary>
/// <returns></returns>
[HttpGet, Route("Reflection")]
public string GetUserInfoByReflection()
{
Assembly ass = Assembly.Load("BLL.dll");
Type type = ass.GetType("BLL.UserBLL");
//调用默认的无参构造函数进行对象的创建
object myUserBll = Activator.CreateInstance(type);
IUserBLL userBll = myUserBll as IUserBLL;
var result = userBll.GetUserInfor();
return result;
} /// <summary>
/// 测试AUTOFAC
/// </summary>
/// <returns></returns>
[HttpGet, Route("testAutofac")]
public string Test()
{
//IUserBLL userBLL = System.Web.Mvc.DependencyResolver.Current.GetService<IUserBLL>();
var builder = new ContainerBuilder();
builder.RegisterType<UserBLL>().As<IUserBLL>();
var container = builder.Build().BeginLifetimeScope();
var userBll = container.Resolve<IUserBLL>();
var result = userBll.GetUserInfor("Autofac");
return result;
//var result = _userBLL.GetUserInfor("Autofac");
//return result;
} /// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet, Route("Assembly")]
public string GetUserInfo()
{
//1、使用nupkg引用Autofac,Autofac.Mvc5和Autofac.Webapi2
//PM > install-package autofac - version 3.5.0
//PM > install-package autofac.mvc5
//PM > install-package autofac.webapi2
//(注意:您的项目中如果使用的是webapi2,此处必须为webapi2而不是webapi,
//否则在运行时将出现“重写成员“Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()”时违反了继承安全性规则。
//重写方法的安全可访问性必须与所重写方法的安全可访问性匹配。”错误。) mvc同样
string strUserInfo = _userBll.GetUserInfor("user-Assembly");
string strPeople = _peopleBll.Introduce("people-Assembly");
string result = strUserInfo + "," + strPeople;
return result;
} // GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} // GET api/<controller>/5
public string Get(int id)
{
return "value";
} // POST api/<controller>
public void Post([FromBody]string value)
{
} // PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
} // DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
UserController
netcore;
//DI了AutoMapper中需要用到的服务,其中包括AutoMapper的配置类 Profile
services.AddAutoMapper();
var builder = new ContainerBuilder();
builder.Populate(services);
builder.RegisterAssemblyTypes(typeof(ManagerRoleRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(ManagerRoleService).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
return new AutofacServiceProvider(builder.Build());
}
netcore 配置
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = new ContainerBuilder();//实例化 AutoFac 容器
var assemblys = Assembly.Load("Service");//Service是继承接口的实现方法类库名称
var baseType = typeof(IDependency);//IDependency 是一个接口(所有要实现依赖注入的借口都要继承该接口)
builder.RegisterAssemblyTypes(assemblys)
.Where(m => baseType.IsAssignableFrom(m) && m != baseType)
.AsImplementedInterfaces().InstancePerLifetimeScope(); builder.Populate(services);
ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);//第三方IOC接管 core内置DI容器 } ConfigureServices方法由void改为返回IServiceProvider
https://www.cnblogs.com/shacoli/p/8523866.html
https://www.cnblogs.com/xujie520/p/5200815.html
https://www.cnblogs.com/yanweidie/p/autofac.html
https://www.cnblogs.com/lenmom/p/9081658.html
https://blog.csdn.net/ad996454914/article/details/80901105
https://www.cnblogs.com/yanweidie/p/autofac.html
Autofac +webapi 配置的更多相关文章
- Autofac 及 Autofac.WebApi 与MVC版本兼容问题
环境:vs2013 下载 Autofac 时,会自动把 Microsoft.AspNet.Mvc 更新到 5.2.3.原来是 5.0.0.0 再使用 Autofac.WebApi , 出现以下问题: ...
- Asp.Net WebAPI配置接口返回数据类型为Json格式
Asp.Net WebAPI配置接口返回数据类型为Json格式 一.默认情况下WebApi 对于没有指定请求数据类型类型的请求,返回数据类型为Xml格式 例如:从浏览器直接输入地址,或者默认的XM ...
- .net core webapi 配置swagger调试界面
一.创建一个.net core webapi的项目: 二.在nuget程序包管理器控制台输入 Install-Package Swashbuckle -version 6.0.0-beta902 ...
- Asp.net WebApi 配置 Swagger UI
首先安装Swashbuckle.Core 然后添加swagger配置文件. [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), &q ...
- Autofac通过配置的方式
autofac是比较简单易用的IOC容器.下面我们展示如何通过json配置文件,来进行控制反转. 需要用到以下程序集.可以通过nugget分别安装 Microsoft.Extensions.Confi ...
- Asp.net Mvc、webApi配置允许跨域
Web.config 下<system.webServer> 节点下配置 <httpProtocol> <customHeaders> <add name=& ...
- C# WebApi 配置复杂路由不生效的问题
配置复杂路由不生效是由于优先级的关系,应该把默认路由放在最后. config.Routes.MapHttpRoute( name: "DynamicApi", routeTempl ...
- asp.net core webapi 配置跨域处理
在Startup.cs文件中的ConfigureServices方法中加入如下代码: //配置跨域处理 services.AddCors(options => { options.AddPoli ...
- webapi框架搭建-依赖注入之autofac
前言 c#的依赖注入框架有unity.autofac,两个博主都用过,感觉unity比较简单而autofac的功能相对更丰富(自然也更复杂一点),本篇将基于前几篇已经创建好的webapi项目,引入au ...
随机推荐
- docker swarm 命令
初始化swarm manager并制定网卡地址 docker swarm init --advertise-addr 192.168.10.117 强制删除集群,如果是manager,需要加–forc ...
- 度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同。度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少?
var data=[10,25,50,10,20,80,30,30,40,90]; function fun(arr,index){ var min=Math.min.apply(this,arr); ...
- poj 3468 A Simple Problem with Integers 线段树区间加,区间查询和(模板)
A Simple Problem with Integers Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://poj.org/problem?i ...
- 【OCP|052】OCP换题库,052最新题库及答案整理-第10题
10.Which two are true about consistent database backups? A) They can only be taken when a RECOVERY C ...
- 量化分析获取数据的3种姿势(压箱底的神器Tushare)
自打入门量化分析起,就有相当部分的时间在与数据打交道,从数据的获取.清洗到使用,对分析而言既是繁琐的,也是必须的.有大牛曾经说,量化分析有8成的开发时间都在处理数据. 为了节省时间,将更多精力投入到策 ...
- es查询,聚合、平均值、值范围、cardinality去重查询
原文:https://blog.csdn.net/sxf_123456/article/details/78195829 普通查询 GET ana-apk/_search { "query& ...
- linux用到的命令
命令行下利用别名打开ss以及设置相关代理(写到~/.bashrc中使永久有效) #open proxy alias proxystart='gsettings set org.gnome.system ...
- 玩转MongoDB
一.主从复制 1)首先主从服务器在启动的时候,分别要设置master.slave选项,对于slave可以启动中设置源,也可以在启动后设置源. 如:主:mongod --dbpath=/data/mon ...
- docker搭建tomcat环境
1.拉取镜像 docker pull tomcat 2.运行容器 docker run --name tomcat -p : -v /data/tomcat/test:/usr/local/tomca ...
- java 使用idea将工程打成jar并创建成exe文件类型执行
https://blog.csdn.net/weixin_38310965/article/details/80392767