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. 删除未加入svn版本控制的文件(包括文件夹)

    删除未加入svn版本控制的文件(包括文件夹) svn status | grep '^?' | awk '{print $2}' | xargs rm -rf

  2. 学习计划 mysql 用户管理与权限

    最近在学习数据库的 主从复制 里面涉及到了关于用户及其管理权限的赋予,之前一直没有认真的学习这个. 现在想具体的学习一下. -- 为什么 数据库 要实现多用户管理? 举个最简单的例子,你需要和第三方做 ...

  3. linux删除指定行&删除行首空格&替换字符

    打印并删除2~1000行 nl /etc/passwd | sed '2,1000d' |more 删除行首空格 sed -i 's/^[][ ]*//g' file 替换分隔符 说明:文件中数据是由 ...

  4. LeetCode-206.ReverseLinked List

    Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4-> ...

  5. 005-四种常见的 POST 提交数据方式

    1.http请求方法 HTTP Method RFC Request Has Body Response Has Body Safe Idempotent Cacheable GET RFC 7231 ...

  6. Linux中Kill掉进程的10种方法

    常规篇: 首先,用ps查看进程,方法如下: 复制代码 代码如下: $ ps -ef……smx 1822 1 0 11:38 ? 00:00:49 gnome-terminalsmx 1823 1822 ...

  7. JavaWeb 服务启动时,在后台启动加载一个线程

    JavaWeb 服务启动时,在后台启动加载一个线程. 目前,我所掌握的一共有两种方法,第一种是监听(Listener),第二种是配置随项目启动而启动的Servlet. 下面对这两种方法做一简单的介绍, ...

  8. javascript unicode与GBK2312(中文)编码转换示例

    一个javascript的unicode与GBK2312编码相互转换的方法. 代码: var GB2312UnicodeConverter = {     ToUnicode: function (s ...

  9. JVM、Java编译器和Java解释器

    作用: JVM:JVM有自己完善的硬件架构,如处理器.堆栈(Stack).寄存器等,还具有相应的指令系统(字节码就是一种指令格式).JVM屏蔽了与具体操作系统平台相关的信息,使得Java程序只需要生成 ...

  10. Javascript-逻辑或(||)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...