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的浸入性要小得多。请参考文章依赖注入容器Autofac - 张善友 - 博客园。他不会像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容器越来受到广大开发者的喜爱。
 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐