我有一个基于MassTransit的Windows服务上托管的应用程序。它针对.net Framework 4.6.2。现在,我将其移植到asp.net core 2.0。在.net框架上,我使用autofac的容器从指定的程序集中加载使用者。现在我要使用默认的asp.net核心的DI。有我的启动代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.RegisterAllTypes<IConsumer>(new Assembly[] { Assembly.Load("consumersLib") });
var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri("rabbithost"), h =>{...});
cfg.ReceiveEndpoint("queue", ec =>
{
ec.LoadFrom(services.BuildServiceProvider());
});
});
}
并注册:
public static void RegisterAllTypes<T>(this IServiceCollection services, Assembly[] assemblies,
ServiceLifetime lifetime = ServiceLifetime.Transient)
{
var typesFromAssemblies = assemblies.SelectMany(a => a.DefinedTypes.Where(x => x.GetInterfaces().Contains(typeof(T))));
foreach (var type in typesFromAssemblies)
services.Add(new ServiceDescriptor(typeof(T), type, lifetime));
}
ec.LoadFrom(services.BuildServiceProvider())引发异常:“对象引用未设置为对象的实例。”即使services.BuildServiceProvider()已初始化并包含一些使用者。我看着masstransit的来源:
public static void LoadFrom(this IReceiveEndpointConfigurator configurator, IServiceProvider serviceProvider)
{
var consumerCache = serviceProvider.GetService<IConsumerCacheService>();
var consumers = consumerCache.GetConfigurators();
foreach (var consumer in consumers)
consumer.Configure(configurator, serviceProvider);
var sagaCache = serviceProvider.GetService<ISagaCacheService>();
IEnumerable<ICachedConfigurator> sagas = sagaCache.GetConfigurators();
foreach (var saga in sagas)
saga.Configure(configurator, serviceProvider);
}
,然后我发现一行serviceProvider.GetService()返回null。有人知道如何解决吗?
答案 0 :(得分:0)
有一个集成库,可将MassTransit与MS DI一起使用。
https://www.nuget.org/packages/MassTransit.Extensions.DependencyInjection/
也有记录:
http://masstransit-project.com/MassTransit/usage/containers/msdi.html