如何使用依赖注入与ASP.NET Web窗体 [英] How to use Dependency Injection with ASP.NET Web Forms

查看:62
本文介绍了如何使用依赖注入与ASP.NET Web窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一种方法来使用依赖注入的ASP.NET Web窗体控件。

I am trying to work out a way to use dependency injection with ASP.NET Web Forms controls.

我有很多是直接创建控件库,并使用这些访问并绑定到数据等。

I have got lots of controls that create repositories directly, and use those to access and bind to data etc.

我要寻找一个模式,我可以通过资源库的外部控制(IOC),所以我的控制依然没有意识到仓库是如何建造和他们来自哪里等。

I am looking for a pattern where I can pass repositories to the controls externally (IoC), so my controls remain unaware of how repositories are constructed and where they come from etc.

我想preFER不要从我的控制IoC容器的依赖关系,因此我只是希望能够构建与控制构造函数或财产注入。

I would prefer not to have a dependency on the IoC container from my controls, therefore I just want to be able to construct the controls with constructor or property injection.

(而就使事情变得复杂,这些控件正在建设并通过CMS在运行时放置在页面上!)

(And just to complicate things, these controls are being constructed and placed on the page by a CMS at runtime!)

有什么想法?

推荐答案

您可以通过使用一个自定义替换默认 PageHandlerFactory 使用自动构造器注入。这样,您就可以使用重载的构造函数加载的依赖关系。您的页面可能是这样的:

You can use automatic constructor injection by replacing the default PageHandlerFactory with a custom one. This way you can use an overloaded constructor to load the dependencies. Your page might look like this:

public partial class HomePage : System.Web.UI.Page
{
    private readonly IDependency dependency;

    public HomePage(IDependency dependency)
    {
        this.dependency = dependency;
    }

    // Do note this protected ctor. You need it for this to work.
    protected HomePage () { }
}

配置的自定义 PageHandlerFactory 可以在web.config进行如下:

Configuring that custom PageHandlerFactory can be done in the web.config as follows:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <httpHandlers>
      <add verb="*" path="*.aspx"
        type="YourApp.CustomPageHandlerFactory, YourApp"/>
    </httpHandlers>
  </system.web>
</configuration>

CustomPageHandlerFactory 可以是这样的:

public class CustomPageHandlerFactory : PageHandlerFactory
{
    private static object GetInstance(Type type)
    {
        // TODO: Get instance using your favorite DI library.
        // for instance using the Common Service Locator:
        return Microsoft.Practices.ServiceLocation
            .ServiceLocator.Current.GetInstance(type);
    }

    public override IHttpHandler GetHandler(HttpContext cxt, 
        string type, string vPath, string path)
    {
        var page = base.GetHandler(cxt, type, vPath, path);

        if (page != null)
        {
            // Magic happens here ;-)
            InjectDependencies(page);
        }

        return page;
    }

    private static void InjectDependencies(object page)
    {
        Type pageType = page.GetType().BaseType;

        var ctor = GetInjectableCtor(pageType);

        if (ctor != null)
        {
            object[] arguments = (
                from parameter in ctor.GetParameters()
                select GetInstance(parameter.ParameterType)
                .ToArray();

            ctor.Invoke(page, arguments);
        }
    }

    private static ConstructorInfo GetInjectableCtor(
        Type type)
    {
        var overloadedPublicConstructors = (
            from constructor in type.GetConstructors()
            where constructor.GetParameters().Length > 0
            select constructor).ToArray();

        if (overloadedPublicConstructors.Length == 0)
        {
            return null;
        }

        if (overloadedPublicConstructors.Length == 1)
        {
            return overloadedPublicConstructors[0];
        }

        throw new Exception(string.Format(
            "The type {0} has multiple public " +
            "ctors and can't be initialized.", type));
    }
}

缺点是,这只能在运行完全信任你身边的时候。您可以阅读更多关于它的此处。但请注意,在部分信任<一个开发ASP.NET应用程序href=\"https://stackoverflow.com/questions/16849801/is-trying-to-develop-for-medium-trust-a-lost-cause\">seems一个失败的事业。

Downside is that this only works when running your side in Full Trust. You can read more about it here. But do note that developing ASP.NET applications in partial trust seems a lost cause.

这篇关于如何使用依赖注入与ASP.NET Web窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆