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里面支持 ...
随机推荐
- short url短链接原理
一.什么是短链接 含义:就是把普通网址,转换成比较短的网址.比如:http://t.cn/RlB2PdD 这种,比如:微博:这些限制字数的应用里都用到这种技术. 优点:短.字符少.美观.便于发布.传播 ...
- Dungeon Master---2251(bfs)
http://poj.org/problem?id=2251 有一个三维的牢房地图 求从S点走E点的最小时间: #include<stdio.h> #include<string.h ...
- 2015 湘潭大学程序设计比赛(Internet)--G题-人生成就
人生成就 Accepted : 54 Submit : 104 Time Limit : 10000 MS Memory Limit : 65536 KB 题目描述 人生就像一个n*n的矩阵, ...
- Python性能鸡汤(转)
英文原文:http://blog.monitis.com/index.php/2012/02/13/python-performance-tips-part-1/ 英文原文:http://blog.m ...
- flask-WTForms组件
WTForms是一个支持多个web框架的form组件 主要能够帮助我们生成html标签 对数据进行验证 安装 pip install wtforms Wtforms的使用 这里借助一个用户登录注册的示 ...
- LeetCode-104.Maxinum Depth of Binary Tree
Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longe ...
- 一次性从git远程仓库中克隆到本地。
自动化工具 一次性从git远程仓库中克隆到本地. import os # git操作 将远程repo克隆到本地 def git_clone_cd_pull(url): # 获取仓库名称 如fullsp ...
- 问题解决 -------- 解决YUM下Loaded plugins: fastestmirror Determining fastest mirrors 的问题
解决YUM下Loaded plugins: fastestmirror Determining fastest mirrors 的问题 (2012-09-02 13:09:25) 转载▼ 标签: 杂谈 ...
- (转)Springboot 中filter 注入对象
问题:我建立一个全局拦截器,当然,这是测试的时候建立的,我把它命名为LogFilter,它继承了Filter,web应用启动的顺序是:listener->filter->servlet,而 ...
- [LeetCode] 196. Delete Duplicate Emails_Easy tag: SQL
Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique ...