使用 Castle Windsor 在 ASP.NET MVC 中设置控制反转 (IoC)

发布于 2024-10-19 10:40:18 字数 2135 浏览 5 评论 0原文

我将回顾 Sanderson 的 Pro ASP.NET MVC 框架,并在第 4 章中讨论 创建自定义控制器工厂 看来原始方法,用于注册控制器的 AddComponentLifeStyleAddComponentWithLifeStyle 现在已弃用:

public class WindsorControllerFactory : DefaultControllerFactory
{
    IWindsorContainer container;

    public WindsorControllerFactory()
    {
        container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));

        // register all the controller types as transient
        var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                              where typeof(IController).IsAssignableFrom(t)
                              select t;

        //[Obsolete("Use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)) instead.")]
        //IWindsorContainer AddComponentLifeStyle<I, T>(string key, LifestyleType lifestyle) where T : class;
        foreach (Type t in controllerTypes)
        {
            container.Register(Component.For<IController>().ImplementedBy<???>().Named(t.FullName).LifeStyle.Is(LifestyleType.Transient));
        }
    }

    // Constructs the controller instance needed to service each request
    protected override IController GetControllerInstance(Type controllerType)
    {
        return (IController)container.Resolve(controllerType);
    }
}

新建议是使用 Register(Component.For().ImplementedBy; ().Named(key).Lifestyle.Is(lifestyle)),但我不知道如何在 ImplementedBy() 中呈现实现控制器类型代码>方法。我尝试了 ImplementedBy()ImplementedBy(),但我找不到传递实现类型的适当方法。有什么想法吗?

I'm going over Sanderson's Pro ASP.NET MVC Framework and in Chapter 4 he discusses Creating a Custom Controller Factory and it seems that the original method, AddComponentLifeStyle or AddComponentWithLifeStyle, used to register controllers is deprecated now:

public class WindsorControllerFactory : DefaultControllerFactory
{
    IWindsorContainer container;

    public WindsorControllerFactory()
    {
        container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));

        // register all the controller types as transient
        var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                              where typeof(IController).IsAssignableFrom(t)
                              select t;

        //[Obsolete("Use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)) instead.")]
        //IWindsorContainer AddComponentLifeStyle<I, T>(string key, LifestyleType lifestyle) where T : class;
        foreach (Type t in controllerTypes)
        {
            container.Register(Component.For<IController>().ImplementedBy<???>().Named(t.FullName).LifeStyle.Is(LifestyleType.Transient));
        }
    }

    // Constructs the controller instance needed to service each request
    protected override IController GetControllerInstance(Type controllerType)
    {
        return (IController)container.Resolve(controllerType);
    }
}

The new suggestion is to use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)), but I can't figure out how to present the implementing controller type in the ImplementedBy<???>() method. I tried ImplementedBy<t>() and ImplementedBy<typeof(t)>(), but I can't find the appropriate way to pass in the implementing type. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

╰沐子 2024-10-26 10:40:18

我正在使用 ControllerBuilder.SetControllerFactory 以及您可以在开源项目 MvcContrib 中找到的代码:

Global.asax.cs

protected void Application_Start()
{
    ...

    IWindsorContainer windsorContainer = new WindsorContainer();
    windsorContainer.RegisterControllers(Assembly.GetExecutingAssembly());
    ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(windsorContainer));

    ...
}

WindsorControllerFactory

public class WindsorControllerFactory : DefaultControllerFactory
{
    private readonly IWindsorContainer _container;

    public WindsorControllerFactory(IWindsorContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException();
        }

        _container = container;
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            throw new HttpException();
        }

        if (!typeof(IController).IsAssignableFrom(controllerType))
        {
            throw new ArgumentException();
        }

        try
        {
            return (IController)_container.Resolve(controllerType);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException();
        }
    }

    public override void ReleaseController(IController controller)
    {
        IDisposable disposable = controller as IDisposable;

        if (disposable != null)
        {
            disposable.Dispose();
        }

        _container.Release(controller);
    }
}

WindsorExtensions (请参阅MvcContrib

public static class WindsorExtensions
{
    public static IWindsorContainer RegisterController<T>(this IWindsorContainer container) where T : IController
    {
        container.RegisterControllers(typeof(T));

        return container;
    }

    public static IWindsorContainer RegisterControllers(this IWindsorContainer container, params Type[] controllerTypes)
    {
        foreach (Type type in controllerTypes)
        {
            if (ControllerExtensions.IsController(type))
            {
                container.Register(Component.For(type).Named(type.FullName).LifeStyle.Is(LifestyleType.Transient));
            }
        }

        return container;
    }

    public static IWindsorContainer RegisterControllers(this IWindsorContainer container, params Assembly[] assemblies)
    {
        foreach (Assembly assembly in assemblies)
        {
            container.RegisterControllers(assembly.GetExportedTypes());
        }

        return container;
    }
}

ControllerExtensions(请参阅MvcContrib)

public static class ControllerExtensions
{
    public static bool IsController(Type type)
    {
        return type != null
               && type.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)
               && !type.IsAbstract
               && typeof(IController).IsAssignableFrom(type);
    }
}

I'm doing this using the ControllerBuilder.SetControllerFactory and the code you can find in the open source project MvcContrib:

Global.asax.cs

protected void Application_Start()
{
    ...

    IWindsorContainer windsorContainer = new WindsorContainer();
    windsorContainer.RegisterControllers(Assembly.GetExecutingAssembly());
    ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(windsorContainer));

    ...
}

WindsorControllerFactory

public class WindsorControllerFactory : DefaultControllerFactory
{
    private readonly IWindsorContainer _container;

    public WindsorControllerFactory(IWindsorContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException();
        }

        _container = container;
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            throw new HttpException();
        }

        if (!typeof(IController).IsAssignableFrom(controllerType))
        {
            throw new ArgumentException();
        }

        try
        {
            return (IController)_container.Resolve(controllerType);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException();
        }
    }

    public override void ReleaseController(IController controller)
    {
        IDisposable disposable = controller as IDisposable;

        if (disposable != null)
        {
            disposable.Dispose();
        }

        _container.Release(controller);
    }
}

WindsorExtensions (see MvcContrib)

public static class WindsorExtensions
{
    public static IWindsorContainer RegisterController<T>(this IWindsorContainer container) where T : IController
    {
        container.RegisterControllers(typeof(T));

        return container;
    }

    public static IWindsorContainer RegisterControllers(this IWindsorContainer container, params Type[] controllerTypes)
    {
        foreach (Type type in controllerTypes)
        {
            if (ControllerExtensions.IsController(type))
            {
                container.Register(Component.For(type).Named(type.FullName).LifeStyle.Is(LifestyleType.Transient));
            }
        }

        return container;
    }

    public static IWindsorContainer RegisterControllers(this IWindsorContainer container, params Assembly[] assemblies)
    {
        foreach (Assembly assembly in assemblies)
        {
            container.RegisterControllers(assembly.GetExportedTypes());
        }

        return container;
    }
}

ControllerExtensions (see MvcContrib)

public static class ControllerExtensions
{
    public static bool IsController(Type type)
    {
        return type != null
               && type.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)
               && !type.IsAbstract
               && typeof(IController).IsAssignableFrom(type);
    }
}
段念尘 2024-10-26 10:40:18

您可能还想考虑在最新的 Windsor 版本中使用新的安装程序选项。有关 Windsor 教程的更多文档: http ://stw.castleproject.org/Windsor.Windsor-tutorial-part-third-writing-your-first-installer.ashx

You may also want to consider using the new installer option in the latest Windsor build. There is more documentation on Windsor's tutorial: http://stw.castleproject.org/Windsor.Windsor-tutorial-part-three-writing-your-first-installer.ashx

浅暮の光 2024-10-26 10:40:18

有一个教程(正在制作中,但 9 部分已经发布)讨论 ASP.NET MVC 中 Windsor 的使用 此处
据我所知,这是最新的,涵盖了该主题的大部分常用资源。

There's a tutorial (in the works but 9 parts are already out) that discusses usage of Windsor in ASP.NET MVC here.
That's the most up to date and covering most of the usual usage resource on the topic as far as I'm aware.

夜巴黎 2024-10-26 10:40:18

@Lirik,作为补充:如果您使用 MVC3,请删除您自己的自定义 IControllerFactory 。只需向 Windsor 注册控制器并在 Windsor 容器内实现 IDependencyResolver 即可。

将您的 IDependencyResolver 设置为 MVC DependencyResolver,并且 DefaultControllerFactory 将自动连接在容器中注册的控制器(通过 DependencyResolver)。

@Lirik, as an addition: drop your own custom IControllerFactory out if you use MVC3. Just register controllers with Windsor and implement IDependencyResolver with Windsor container inside.

Set your IDependencyResolver as MVC DependencyResolver and DefaultControllerFactory will automatically wire up controllers registered in container (via DependencyResolver).

猥琐帝 2024-10-26 10:40:18

类似于:

public void Register(IWindsorContainer container)
    {
        Assembly.GetAssembly(typeof(ControllersRegistrarMarker)).GetExportedTypes()
                .Where(IsController)
                .Each(type => container.AddComponentLifeStyle(
                                      type.Name.ToLower(),
                                      type,
                                      LifestyleType.Transient));
    }

ControllersRegistrarMarker 只是控制器程序集中的一个空类

something like:

public void Register(IWindsorContainer container)
    {
        Assembly.GetAssembly(typeof(ControllersRegistrarMarker)).GetExportedTypes()
                .Where(IsController)
                .Each(type => container.AddComponentLifeStyle(
                                      type.Name.ToLower(),
                                      type,
                                      LifestyleType.Transient));
    }

ControllersRegistrarMarker is just an empty class in your Controllers assembly

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文