Autofac相当于这个Ninject代码的是什么?

时间:2013-12-11 01:52:07

标签: c# signalr ninject autofac

在以下页面: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) { }
}

1 个答案:

答案 0 :(得分:12)

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。这应该有用。