编程语言
首页 > 编程语言> > C#-Ninject绑定到需要当前Request.Url的类型

C#-Ninject绑定到需要当前Request.Url的类型

作者:互联网

我正在基于MVC5的网站中使用Ninject 3,并试图弄清楚如何使DI与测试传递给其构造函数的Uri.Host值的属性的类型一起使用.我想要以某种方式提供当前URL的绑定.我最初尝试的最小结构是:

public class StructuredUrlTester : IStructuredUrlTester
{
    // Expose public getters for parts of the uri.Host value
    bool MyBooleanProperty { get; private set; }

    public StructuredUrlTester(Uri uri)
    {
        // Test the value of uri.Host and extract parts via regex
    }
}

// In Global.asax.cs
public class MvcApplication : NinjectHttpApplication
{
    protected override IKernel CreateKernel()
    {
        kernel.Bind<IStructuredUrlTester>()
            .To<StructuredUrlTester>()
            .InTransientScope();
            .WithConstructorArgument("uri", Request.Url);
    }
}

// In MyController.cs
public class MyController : Controller
{
    private readonly IStructuredUrlTester _tester;

    public ContentPageController(IStructuredUrlTester tester)
    {
        this._tester = tester;
    }

    public ActionResult Index()
    {
        string viewName = "DefaultView";
        if (this._tester.MyBooleanProperty)
        {
            viewName = "CustomView";
        }

        return View(viewName);
    }
}

由于CreateKernel()调用发生在Request对象可用之前,因此.WithConstructorArgument()部分会引发异常(“ System.Web.HttpException:请求在此上下文中不可用”).

我如何提供接口与具体类型的绑定,同时还能提供例如HttpContext.Current.Request.Url值(在Controller内可用)到具体类型的构造函数,是否在运行时可用?

解决方法:

将所需的功能抽象化:

public interface IUriProvider {
    Uri Current { get; }
}

重构测试器类:

public class StructuredUrlTester : IStructuredUrlTester {
    // Expose public getters for parts of the uri.Host value
    bool MyBooleanProperty { get; private set; }

    public StructuredUrlTester(IUriProvider provider) {
        Uri uri = provider.Current;
        // Test the value of uri.Host and extract parts via regex
    }
}

提供者实现应包装Request.Url:

public class UriProvider : IUriProvider {
    public Uri Current { get { return  HttpContext.Current.Request.Url; } }
}

并请注意,Current属性实际上应在有HttpContext及其请求可用的控制器的动作内调用.

标签:asp-net-mvc-5,dependency-injection,ninject,c
来源: https://codeday.me/bug/20191111/2021632.html