zoukankan      html  css  js  c++  java
  • 注册接口使用StructureMap和Autofac等Ioc容器注册接口

    本文笔者在广东游玩的时候突然想到的...今天就有想写几篇关于注册接口的文章,所以回家到之后就奋笔疾书的写出来发表了

        1、StructureMap应用

        StructureMap是通过定义一个StructureMapControllerFactory替换默许的DefaultControllerFactory,在Application_Start行进接口的注册。体具的应用网上已经有很多程教,这里就不多做绍介了。在这里要讲的是应用StructureMap做ico器容时HandleError性属会不起作用,据网上说可以修改Global件文中的RegisterGlobalFilters方法,但是总觉得用上去非常不爽,有些mvc有的特性用不了了,可见StructureMap的侵入性是比大较的。同时StructureMap不持支Filter Attribute注入,只能通过态静工厂实当初Filter Attribute中应用接口,如写重AuthorizeAttribute授权性属:

    /// <summary>
    /// 写重授权机制
    /// </summary>
    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        private readonly ILocalAuthenticationService _authenticationService =
            AuthenticationFactory.GetLocalAuthenticationService();
    
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
    
            var cookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie == null)
                return false;
            if (string.IsNullOrEmpty(cookie["username"]))
                return false;
            if (string.IsNullOrEmpty(cookie["usertoken"]))
                return false;
    
            if (!_authenticationService.ValidateAuthenticationToken(cookie["username"], cookie["usertoken"]))
                return false;
    
            return true;
        }
    }

        我们须要建一个工厂才可以在AuthorizeAttribute中应用接口。AuthenticationFactory如下

    public class AuthenticationFactory
    {
        private static ILocalAuthenticationService _authenticationService;
    
        public static void InitializeAuthenticationFactory(
            ILocalAuthenticationService authenticationService)
        {
            _authenticationService = authenticationService;
        }
    
        public static ILocalAuthenticationService GetLocalAuthenticationService()
        {
            return _authenticationService;
        }
    }

        同时还要在Application_Start对接口行进初始化。

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        BootStrapper.ConfigureDependencies();
    
        AuthenticationFactory.InitializeAuthenticationFactory
                                (ObjectFactory.GetInstance<ILocalAuthenticationService>());
    
        ApplicationSettingsFactory.InitializeApplicationSettingsFactory
                                (ObjectFactory.GetInstance<IApplicationSettings>());
    
        LoggingFactory.InitializeLogFactory(ObjectFactory.GetInstance<ILogger>());
    
        EmailServiceFactory.InitializeEmailServiceFactory
                                (ObjectFactory.GetInstance<IEmailService>());
        ObjectFactory.GetInstance<ILogger>().Log("程序开始了");
    
        ControllerBuilder.Current.SetControllerFactory(new IoCControllerFactory());
    
        //移除过剩的视图引擎
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());
    
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

        2、Autofac应用

        对相StructureMap说来,Autofac的浸入性要小得多。请考参文章http://www.cnblogs.com/shanyou/archive/2010/02/07/1665451.html。他不会像StructureMap会致导mvc特性失效。同时持支性属注入。

        每日一道理
    正所谓“学海无涯”。我们正像一群群鱼儿在茫茫的知识之海中跳跃、 嬉戏,在知识之海中出生、成长、生活。我们离不开这维持生活的“海水”,如果跳出这个“海洋”,到“陆地”上去生活,我们就会被无情的“太阳”晒死。
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        var builder = new ContainerBuilder();
        //注册控制器
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        //注册Filter Attribute
        builder.RegisterFilterProvider();
    
        //注册各种
        ContainerManager.SetupResolveRules(builder);
    
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    
        //初始化各种工厂
        AuthenticationFactory.InitializeAuthenticationFactory(container.Resolve<ILocalAuthenticationService>());
        ApplicationSettingsFactory.InitializeApplicationSettingsFactory(container.Resolve<IApplicationSettings>());
        EmailServiceFactory.InitializeEmailServiceFactory(container.Resolve<IEmailService>());
        LoggingFactory.InitializeLogFactory(container.Resolve<ILogger>());
    
        container.Resolve<ILogger>().Log("哇!程序开始了!");
    
        //移除过剩的视图引擎
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());
    
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

        Filter Attribute注入

    /// <summary>
    /// 写重授权机制
    /// </summary>
    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        //private readonly ILocalAuthenticationService _authenticationService =
        //    AuthenticationFactory.GetLocalAuthenticationService();
        public ILocalAuthenticationService _authenticationService { get; set; }
    
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
    
            var cookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie == null)
                return false;
            if (string.IsNullOrEmpty(cookie["username"]))
                return false;
            if (string.IsNullOrEmpty(cookie["usertoken"]))
                return false;
    
            if (!_authenticationService.ValidateAuthenticationToken(cookie["username"], cookie["usertoken"]))
                return false;
    
            return true;
        }
    }

        ContainerManager类中注册各种接口

    public class ContainerManager
    {
        public static void SetupResolveRules(ContainerBuilder builder)
        {
            builder.RegisterType<UserRepository>().As<IUserRepository>();
            builder.RegisterType<UserGroupRepository>().As<IUserGroupRepository>();
            builder.RegisterType<SqlServrUnitOfWork>().As<IUnitOfWork>();
    
            builder.RegisterType<UserService>().As<IUserService>();
            builder.RegisterType<UserGroupService>().As<IUserGroupService>();
            builder.RegisterType<EncryptionService>().As<IEncryptionService>();
            builder.RegisterType<JwayAuthenticationService>().As<ILocalAuthenticationService>();
            builder.RegisterType<SMTPService>().As<IEmailService>();
            builder.RegisterType<Log4NetAdapter>().As<ILogger>();
            builder.RegisterType<WebConfigApplicationSettings>().As<IApplicationSettings>();
        }
    }

        Autofac的其他注册式形请考参http://code.google.com/p/autofac/wiki/MvcIntegration3
    随着Repository模式的普遍应用,Ioc器容越来遭到大广开发者的爱好。

        

        

    文章结束给大家分享下程序员的一些笑话语录: 一位程序员去海边游泳,由于水性不佳,游不回岸了,于是他挥着手臂,大声求.救:“F1,F1!”

  • 相关阅读:
    数据库设计:数据库设计步骤,er图,三大范式
    连接查询
    连接查询和分组查询
    Django项目的创建与配置
    WEB框架的原理总结
    RabbitMQ---消息队列
    Djang之基于角色的权限控制(RBAC)
    Django之基于RBAC权限控制生成动态菜单
    关于装饰器的一些小练习
    关于简单的python函数的一些小练习题
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3033369.html
Copyright © 2011-2022 走看看