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里面支持 ...
随机推荐
- Best Cow Line---poj3617(贪心)
题目链接:http://poj.org/problem?id=3617 题意:有n头牛.刚开始有一个序列.现在想要重新排列.每次从原始的序列头部和尾部取出一个取出一个放到新的序列尾部.最后使得得到的新 ...
- Networking---poj1287最小生成树
http://poj.org/problem?id=1287 最小生成树模板题类似的还有:poj1258 hdu1233代码几乎一样: 最小生成树详解 #include<stdio.h> ...
- 获取图片的大小(宽高):BytesIO
获取图片的大小(宽高) from io import BytesIO,StringIO import requests from PIL import Image img_url = "ht ...
- PHP消息队列实现及应用_慕课网学习
https://blog.csdn.net/d_g_h/article/details/79643714 https://blog.csdn.net/tTU1EvLDeLFq5btqiK/articl ...
- [py][mx]django课程页显示city和机构封面图
city和课程机构信息展示到前台去 organization/views.py from django.views.generic.base import View from organization ...
- [py]监控内存并出图
监控内存出图 先将内存数据搞到数据库 已使用内存算法 used = int(total) - int(free) - int(butffers) - int(cache) pymysql模块使用 db ...
- (转)Elasticsearch分析聚合
Elasticsearch不仅仅适合做全文检索,分析聚合功能也很好用.下面通过实例来学习. 一.准备数据 {"index":{ "_index": " ...
- Hat's Fibonacci
http://acm.hdu.edu.cn/showproblem.php?pid=1250 大数斐波那契 %08d是什么东西,为什么我用flag交不上,唉,不刷大数了,没劲.暑假再讲. 就是交不上 ...
- Linux实验楼学习之三
查看用户 who am i or who mom likes who 命令其它常用参数 参数 说明 -a 打印能打印的全部 -d 打印死掉的进程 -m 同am i,mom likes -q 打印当前登 ...
- list的*运算使用过程中遇到的问题
目的: 想生成一个[[],[],[]] 这样的列表, 所以就 [[]]*3 这样做了,但是这样做会有问题,这样list中的三个list其实是同一个list. 例如:a=[[]]*3,然后a[0].ap ...