• 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

  • 相关阅读:
    多线程执行有返回值有参数的方法
    当连续进行多个请求,并且请求的url地址相同时。放弃前面的所有请求,只执行最后一次请求。
    防止重复发送Ajax请求的解决方案
    多行文本溢出显示省略号
    h5 文件跨域上传
    完美解决 IOS系统safari5.0 浏览器页面布局iframe滚动条失效问题,iossafari5.0
    CSS3 修改和去除移动端点击事件出现的背景框 (tap-highlight-color)
    去除img之间的空白
    手机上点击a标签是出现阴影解决办法
    idea通过maven构建springMVC+mybatis项目
  • 原文地址:https://www.cnblogs.com/hongdada/p/8082238.html
Copyright © 2020-2023  润新知