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一致的参数类型,并将对象注入到类中,其实就是将对象赋值给构造函数的参数)