使用StructureMap和Autofac等Ioc容器

1 篇文章 0 订阅
1 篇文章 0 订阅

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容器越来受到广大开发者的喜爱。
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在WPF中使用IoC容器可以让代码更加灵活、可扩展和易于维护。常见的IoC容器Autofac、Unity、StructureMap等。 下面以Autofac为例,介绍如何在WPF中进行IoC容器注册。 1. 安装Autofac NuGet包 在Visual Studio中打开NuGet包管理器控制台,执行以下命令: ``` Install-Package Autofac ``` 2. 创建一个IoC容器 在App.xaml.cs文件中创建一个静态的Autofac容器: ```csharp public partial class App : Application { public static IContainer Container { get; private set; } protected override void OnStartup(StartupEventArgs e) { // 创建一个IoC容器 var builder = new ContainerBuilder(); // 注册依赖关系 builder.RegisterType<MyService>().As<IMyService>(); // 构建容器 Container = builder.Build(); base.OnStartup(e); } } ``` 在这个例子中,我们注册了一个名为MyService的服务,并将其标记为IMyService接口的实现类型。 3. 在应用程序中使用IoC容器 在需要使用服务的地方,我们可以使用容器解析服务的实例。 ```csharp public partial class MainWindow : Window { private readonly IMyService _myService; public MainWindow() { InitializeComponent(); // 通过IoC容器获取MyService的实例 _myService = App.Container.Resolve<IMyService>(); } } ``` 在这个例子中,我们使用IoC容器解析MyService的实例,并将其保存在_myService字段中。这样,在MainWindow类中就可以使用_myService字段调用MyService中的方法了。 通过这种方式,我们可以实现依赖注入,减少代码的耦合性,提高应用程序的可扩展性和易于维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值