c# – Autofac与Ninject代码相同的是什么?

前端之家收集整理的这篇文章主要介绍了c# – Autofac与Ninject代码相同的是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下一页http://www.asp.net/signalr/overview/signalr-20/extensibility/dependency-injection

底部附近(正好在文本“RegisterHubs.Start”下方),我试图使用Autofac重现一段Ninject代码.

到目前为止,我已经成功地让自己头痛,但没有多少.我已经搜索了Autofac wiki和网页以获得一些帮助.虽然,我相信我可能错过了一些信息.

更新:这是页面上的相关Ninject代码.

public static class RegisterHubs
{
    public static void Start()
    {
        var kernel = new StandardKernel();
        var resolver = new NinjectSignalRDependencyResolver(kernel);

        kernel.Bind<IStockTicker>()
            .To<Microsoft.AspNet.SignalR.StockTicker.StockTicker>()
            .InSingletonScope();

        kernel.Bind<IHubConnectionContext>().ToMethod(context =>
                resolver.Resolve<IConnectionManager>().
                    GetHubContext<StockTickerHub>().Clients
            ).WhenInjectedInto<IStockTicker>();

        var config = new HubConfiguration()
        {
            Resolver = resolver
        };

        App.MapSignalR(config);
    }
}

更新2:我还想添加试图编写的对象.

public class StockTickerHub : Hub
{
    private readonly IStockTicker _stockTicker;

    public StockTickerHub(IStockTicker stockTicker) { }
}

public class StockTicker
{
    public StockTicker(IHubConnectionContext clients) { }
}

解决方法

Autofac没有等效的WhenInjectedInto方法.但是,您可以使用命名参数完成相同的操作.

尝试这样的事情

using Autofac.Integration.SignalR;
using Microsoft.AspNet.SignalR.StockTicker;

public static class RegisterHubs
{
    public static void Start() 
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<StockTicker>()
            .WithParameter(ResolvedParameter.ForNamed("StockTickerContext"))
            .As<IStockTicker>()
            .SingleInstance();

        builder.Register(c => GlobalHost.DependencyResolver.Resolve<IConnectionManager>().GetHubContext<StockTickerHub>().Clients)
            .Named<IHubConnectionContext>("StockTickerContext");

        var container = builder.Build();

        var resolver = new AutofacDependencyResolver(container);

        var config = new HubConfiguration { Resolver = resolver };

        App.MapSignalR(config);
    }
}

注意:AutofacDependencyResolver来自Autofac.Integration.SignalR.

更新:啊,我错过了链接页面上的一个小细节; IHubConnectionContext的工厂函数使用解析器来获取IConnectionManager,而不是容器本身(当然容器不会知道IConnectionManager).我切换到使用默认依赖项解析器(GlobalHost.DependencyResolver)来获取IConnectionManager.这应该工作.

原文链接:https://www.f2er.com/csharp/101024.html

猜你在找的C#相关文章