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 手动获取接口实例的更多相关文章

  1. 如何手动获取Spring容器中的bean(ApplicationContextAware 接口)

    ApplicationContextAware 接口的作用 先来看下Spring API 中对于 ApplicationContextAware 这个接口的描述:   即是说,当一个类实现了这个接口之 ...

  2. Java Class类以及获取Class实例的三种方式

    T - 由此 Class 对象建模的类的类型.例如,String.class 的类型是Class<String>.如果将被建模的类未知,则使用Class<?>.   publi ...

  3. 转:微信开发获取地理位置实例(java,非常详细,附工程源码)

    微信开发获取地理位置实例(java,非常详细,附工程源码)   在本篇博客之前,博主已经写了4篇关于微信相关文章,其中三篇是本文基础: 1.微信开发之入门教程,该文章详细讲解了企业号体验号免费申请与一 ...

  4. Thinkphp3.2.3框架下封装公共的函数,例如封装CURL函数来获取接口数据

    当我们需要在控制层调用相同的封装函数时,写多次相同的函数,显得代码十分的拉杂,不精简: TP框架有一个很好的机制,可以再Common定义一个function.php函数,当我们在控制层调用的时候直接调 ...

  5. ASP.NET Core DI 手动获取注入对象

    ASP.NET Core DI 一般使用构造函数注入获取对象,比如在ConfigureServices配置注入后,通过下面方式获取: private IValueService _valueServi ...

  6. 手动获取被spring管理的bean对象工具

       在netty handler开发中,我们无法将spring的依赖注入到Handler中,无法进行数据库的操作,这时候我们就需要手动获取被spring管理的bean对象:    创建一个  imp ...

  7. WCF接口实例介绍

    Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台. WCF整合了原有的windows通讯 ...

  8. struts2中action手动获取參数

    struts2中action手动获取Session,jsp页面參数 1. ActionContext 在Struts2开发中,除了将请求參数自己主动设置到Action的字段中,我们往往也须要在Acti ...

  9. Easy-Mock模拟get接口和post接口实例

    1.先创建项目,再新建接口 创建项目入口:首页右下角 + 按钮 创建接口入口如下图: 关于mock的语法这里不做说明,可查看mock.js官方查看更详情的资料. 小tip:在Easy-Mock里面支持 ...

随机推荐

  1. LightOj 1104 - Birthday Paradox(生日悖论概率)

    题目链接:http://lightoj.com/volume_showproblem.php?problem=1104 题意:一年365天,在有23个人的情况下,这23个人中有两个人生日相同的概率是大 ...

  2. web window pixel等笔记

    原文:http://www.w3cplus.com/css/viewports.html 屏幕尺寸 Screen size =显示器尺寸 screen.width 和 screen.height.这两 ...

  3. 【Pyton】【小甲鱼】异常处理:你不可能总是对的

    Exception 1.assertionerror举例 >>> my_list=['小甲鱼是帅哥'] >>> assert len(my_list)>0 & ...

  4. HTML5 脚本 语言代码 URL 符号实体 ASCII码 颜色

    1.HTML<noscript> 标签 <noscript> 标签提供无法使用脚本时的替代内容,比方在浏览器禁用脚本时,或浏览器不支持客户端脚本时. <noscript& ...

  5. sklearn总览

  6. unity3D中 material中tiling和offset属性解释

    贴图有可能是多行多列的一些图案组成的.当我们需要一帧,一帧的播放时候.也就是帧序列动画, 我们就需要用到tiling和offset两个属性, 默认图片的左下角为坐标圆点即:(0,0) tiling是图 ...

  7. ShuffleElements(随机打乱数组中的元素)

    给定一个数组,随机打乱数组中的元素,题意很简单直接上代码: package Array; import java.util.Arrays; import java.util.Collections; ...

  8. 【最大连接数】Linux的文件最大连接数

    Too many open files ==================================== 查看当前操作系统连接数设置 ulimit -a =================== ...

  9. linux常用命令:chgrp 命令

    在 lunix系统里,文件或目录的权限的掌控以拥有者及所诉群组来管理.可以使用chgrp指令变更文件与目录所属群组,这种方式采用群组名称或群组识别 码都可以.chgrp命令就是change group ...

  10. Linux基础命令---findfs

    findfs 查找指定卷标或者UUID的文件系统对应的设备文件.findfs将搜索系统中的磁盘,寻找具有标签匹配标签或与UUID相等的文件系统.如果找到文件系统,文件系统的设备名称将打印在stdout ...