码迷,mamicode.com
首页 > Windows程序 > 详细

Asp.net MVC 和Asp.net.WebApi项目使用AutoFac基础

时间:2020-05-13 16:41:02      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:assign   自动   sync   new   service   returns   构造   ssi   oba   

1 Asp.net MVC 项目使用AutoFace基础

//创建容器
var builder = new ContainerBuilder();
//注册程序集所有控制器Controllers PropertiesAutowired 控制器属性自动注入
builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
// 获取所有相关类库的程序集
Assembly[] assemblies = new Assembly[] {Assembly.Load("TaskAsync.Service") };

builder.RegisterAssemblyTypes(assemblies).Where(t => !t.IsAbstract).AsImplementedInterfaces()
.PropertiesAutowired();
var container = builder.Build();
//注册系统级别的 DependencyResolver,这样当 MVC 框架创建 Controller 等对象的时候都是管 Autofac 要对象
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

2Asp.net.WebApi项目使用AutoFac基础

新建空类IDependency 所有接口类继承 IDependency 

public interface IDependency
{
}

/// <summary>
/// token IService
/// </summary>
public interface ITokenService:IDependency
{
/// <summary>
/// 保存Token
/// </summary>
/// <param name="model">输入数据</param>
/// <returns></returns>
ReturnValueModel<object> Save(TokenSaveModel model);

/// <summary>
/// 删除Token
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
bool Delete(string token);
}

var serviceName = ConfigurationManager.AppSettings["service"];

var builder = new ContainerBuilder();
var baseType = typeof(IDependency);

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(Assembly.Load(serviceName))
.Where(item => baseType.IsAssignableFrom(item))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();

//注册系统级别的 DependencyResolver

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

控制器通过构造函数实现注解

public class TokenController : ApiController
{
/// <summary>
/// token服务
/// </summary>
private ITokenService _iTokenService;

public TokenController(ITokenService iTokenService)
{
_iTokenService = iTokenService;
}

}

Asp.net MVC 和Asp.net.WebApi项目使用AutoFac基础

标签:assign   自动   sync   new   service   returns   构造   ssi   oba   

原文地址:https://www.cnblogs.com/xinghai1/p/12882855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!