Autoafc 手动获取接口实例
demo:
using Autofac;
using Autofac.Integration.Mvc;
using Rongzi.RZR.Huoke.Repository;
using Rongzi.RZR.Huoke.Service;
using Rongzi.RZR.Huoke.Service.MQ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using Rongzi.RZR.Huoke.Repository.Account;
using System.IO;
using Rongzi.RZR.Huoke.Infrastructure.Dependency;
using Rongzi.RZR.Huoke.Service.Services;
using Autofac.Core.Lifetime; namespace Rongzi.RZR.Huoke
{
public class ContainerConfig
{
public static IContainer BuildUnityContainer()
{
var builder = new ContainerBuilder();
RegisterTypes(builder); return builder.Build();
} private static void RegisterTypes(ContainerBuilder builder)
{
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); #region register service
builder.RegisterType<AccountService>().PropertiesAutowired();
builder.RegisterType<HomeService>().PropertiesAutowired();
builder.RegisterType<SettingsService>().PropertiesAutowired();
builder.RegisterType<ImageValidateService>().PropertiesAutowired();
builder.RegisterType<SmsValidDateService>().PropertiesAutowired();
builder.RegisterType<CommonService>().PropertiesAutowired();
builder.RegisterType<LayoutHelper>().PropertiesAutowired();
builder.RegisterType<AdminUtmSourceService>().PropertiesAutowired();
#endregion #region register respository
builder.RegisterType<OrganizationRespository>();
builder.RegisterType<OrganizationUserRepository>();
builder.RegisterType<RequirementBookRespository>();
builder.RegisterType<OrganizationDayStatisticsRepository>();
builder.RegisterType<CustomRespository>();
builder.RegisterType<BaseDataRespository>(); builder.RegisterType<AdminUtmSourceRepository>();
#endregion
} public static T Resolve<T>(string key = "", ILifetimeScope scope = null) where T : class
{
if (scope == null)
{
//no scope specified
scope = Scope();
}
if (string.IsNullOrEmpty(key))
{
return scope.Resolve<T>();
}
return scope.ResolveKeyed<T>(key);
} public static ILifetimeScope Scope()
{
try
{
if (HttpContext.Current != null)
return AutofacDependencyResolver.Current.RequestLifetimeScope; //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
return BuildUnityContainer().BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
}
catch (Exception)
{
//we can get an exception here if RequestLifetimeScope is already disposed
//for example, requested in or after "Application_EndRequest" handler
//but note that usually it should never happen //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
return BuildUnityContainer().BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
}
}
}
}
调用:
namespace Rongzi.RZR.Huoke.Filters
{
public class ApiFormAuthFilterAttribute : System.Web.Mvc.ActionFilterAttribute
{
public AccountService AccountService { get; set; } public ApiFormAuthFilterAttribute()
{
this.AccountService = ContainerConfig.Resolve<AccountService>();
} public override void OnActionExecuting(ActionExecutingContext actionContext)
{
if (actionContext == null || actionContext.HttpContext.Request == null || actionContext.HttpContext.Request.RawUrl == null) { return; }
string OrgUserAccountInfo = actionContext.HttpContext.Request.QueryString["OrgUserAccountInfo"];
if (!String.IsNullOrEmpty(OrgUserAccountInfo))
{
OrgUserAccountInfo info = new RSAEncryptHelper().DecryptString<OrgUserAccountInfo>(OrgUserAccountInfo);
OrganizationUserModel oUser = AccountService.GetOrganizationUserByPhone(info.CellPhone);
if (oUser == null || oUser.OrgId!=info.OrgId)
{
actionContext.Result = GetAuthJsonResult("手机号或机构id错误"); return;
}
if (DateTime.Now.AddMinutes(-10) > info.timespan)
{
actionContext.Result = GetAuthJsonResult("该链接已超时"); return;
}
FormsAuth.SignIn(oUser);
base.OnActionExecuting(actionContext);
return;
}
base.OnActionExecuting(actionContext);
} public static JsonResult GetAuthJsonResult(string msg = "用户还未登录")
{
var errResponse = new ResponseContext<string>();
errResponse.Head = new ResponseHead(-2, ErrCode.AuthError, msg);
return new JsonResult
{
Data = errResponse,
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
} public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
}
}
}
var obj = container.Resolve<Interface>(); //只有有特殊需求的时候可以通过这样的形式来拿。一般情况下没有必要这样来拿,因为AutoFac会自动工作
(即:会自动去类的带参数的构造函数中找与容器中key一致的参数类型,并将对象注入到类中,其实就是将对象赋值给构造函数的参数)
http://blog.csdn.net/fanbin168/article/details/51293218
https://www.cnblogs.com/niuww/p/5649632.html
Autoafc 手动获取接口实例的更多相关文章
- 如何手动获取Spring容器中的bean(ApplicationContextAware 接口)
ApplicationContextAware 接口的作用 先来看下Spring API 中对于 ApplicationContextAware 这个接口的描述: 即是说,当一个类实现了这个接口之 ...
- Java Class类以及获取Class实例的三种方式
T - 由此 Class 对象建模的类的类型.例如,String.class 的类型是Class<String>.如果将被建模的类未知,则使用Class<?>. publi ...
- 转:微信开发获取地理位置实例(java,非常详细,附工程源码)
微信开发获取地理位置实例(java,非常详细,附工程源码) 在本篇博客之前,博主已经写了4篇关于微信相关文章,其中三篇是本文基础: 1.微信开发之入门教程,该文章详细讲解了企业号体验号免费申请与一 ...
- Thinkphp3.2.3框架下封装公共的函数,例如封装CURL函数来获取接口数据
当我们需要在控制层调用相同的封装函数时,写多次相同的函数,显得代码十分的拉杂,不精简: TP框架有一个很好的机制,可以再Common定义一个function.php函数,当我们在控制层调用的时候直接调 ...
- ASP.NET Core DI 手动获取注入对象
ASP.NET Core DI 一般使用构造函数注入获取对象,比如在ConfigureServices配置注入后,通过下面方式获取: private IValueService _valueServi ...
- 手动获取被spring管理的bean对象工具
在netty handler开发中,我们无法将spring的依赖注入到Handler中,无法进行数据库的操作,这时候我们就需要手动获取被spring管理的bean对象: 创建一个 imp ...
- WCF接口实例介绍
Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台. WCF整合了原有的windows通讯 ...
- struts2中action手动获取參数
struts2中action手动获取Session,jsp页面參数 1. ActionContext 在Struts2开发中,除了将请求參数自己主动设置到Action的字段中,我们往往也须要在Acti ...
- Easy-Mock模拟get接口和post接口实例
1.先创建项目,再新建接口 创建项目入口:首页右下角 + 按钮 创建接口入口如下图: 关于mock的语法这里不做说明,可查看mock.js官方查看更详情的资料. 小tip:在Easy-Mock里面支持 ...
随机推荐
- c字符检测函数
isalpha(c) /*判断是否为英文字符*/iscntrl(c) /*判断是否为控制字符*/ isdigit(c) /*判断是否为阿拉伯数字0到9*/isgraph(c) ...
- CF1053E Euler tour 构造
正解:构造 解题报告: 传送门! 这种题目一般都是首先考虑合法性 这题也不例外,思考怎么样是合法的呢? 有四点: 1)a[1]=a[2n-1],显然不说 2)若a[i]=a[j],则(j-i)& ...
- Java非静态内部类为什么不能有静态成员
我们可以把InnerClass看成OuterClass的非静态成员,它的初始化必须在外部类对象创建后以后进行,要加载InnerClass必须在实例化OuterClass之后完成 ,java虚拟机要求所 ...
- Hibernate错误
1.Field 'id' doesn't have a default value 原来是我的数据设计的时候,把主键的类型定义为int的,原本想是用自增的方式来的,可是由于自己的粗心,写sql语句的时 ...
- python课件-淘宝-目录.txt
卷 TOSHIBA EXT 的文件夹 PATH 列表卷序列号为 AE86-8E8DF:.│ python课件-淘宝-目录.txt│ ├─01python核心编程阶段-linux基础(│ linux_h ...
- sql优化 性能快速定位
sql server sql性能快速定位 简介 对于写出实现功能的SQL语句和既能实现功能又能保证性能的SQL语句的差别是巨大的.很多时候开发人员仅仅是把精力放在实现所需的功能上,而忽略了其所写代码的 ...
- PAT 1087 All Roads Lead to Rome[图论][迪杰斯特拉+dfs]
1087 All Roads Lead to Rome (30)(30 分) Indeed there are many different tourist routes from our city ...
- Linux环境下解压rar文件
可以用unrar命令解压rar后缀的文件 unrar e test.rar 解压文件到当前目录 unrar x test.rar /path/to/extract unrar l test.rar 查 ...
-  
这个东西在 html 里是空格占位符,普通的空格在 html 里如果连续的多个可能被认为只有一个,而这个东西你写几个就能占几个空格位.
- soapUI-DataGen
1.1.1 DataGen 1.1.1.1 概述 – DataGen DataGen TestStep可用于生成要用作TestCases中的输入的数据,例如数字或日期序列,随机选择等.生成的数据可作 ...