无法解析“Microsoft.AspNetCore.Hosting.IHostingEnvironment”类型的服务

时间:2017-09-07 17:15:47

标签: c# rabbitmq

在我的MVC应用程序中,我从RabbitMQ队列中获取一个事件。开始处理事件

public void Consume()
{
    ConnectionFactory factory = new ConnectionFactory
    {
        //..
    };

    IConnection connection = factory.CreateConnection();
    IModel channel = connection.CreateModel();
    channel.QueueDeclare("MyQueueName", true, false, false, null);

    EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
    consumer.Received += OnReceived;
    channel.BasicConsume("MyQueueName", true, consumer);
}

要处理我使用的事件

private async void OnReceived(object model, BasicDeliverEventArgs deliverEventArgs)
{
    var info = Encoding.UTF8.GetString(deliverEventArgs.Body);            
    var model = JsonConvert.DeserializeObject<MyModel>(info);
    if (model != null)
    {
        await _groupServiceProvider.GetService<IMyService>().ProcessEvent(model);
    }
}

最后,为了处理/更新我的模型,我使用

public class MyService : IMyService
{
    private readonly IHostingEnvironment _env;

    public MyService(IHostingEnvironment env)
    {
        _env = env;
    }        

    public async Task ProcessEvent(MyModel model)
    {
        //.. process model
    }        
}

不幸的是,当我运行我的应用程序时,我得到了

  

尝试激活“MyProject.MyService”时,无法解析“Microsoft.AspNetCore.Hosting.IHostingEnvironment”类型的服务。

     

at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider,ISet 1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet 1 callSiteChain)      在Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService服务,ISet 1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet 1 callSiteChain)      在Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(类型serviceType,ServiceProvider serviceProvider)      at System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd [TKey,TValue,TArg](ConcurrentDictionary 2 dictionary, TKey key, Func 3 valueFactory,TArg arg)      在Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(类型serviceType)      在Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService [T](IServiceProvider提供程序)      at MyService.Consumerd _3.3.MoveNext()in .. \ MyService \ Consumers.cs:line

有人可以解释我如何解决依赖关系吗?

修改

要注入依赖项,我使用 Microsoft.Extensions.DependencyInjection.ServiceCollection

_groupServiceProvider = new ServiceCollection()                
             .AddAutoMapper(typeof(AutoMapperProfile)) 
             .AddSingleton<IMyService, MyService>()                
             .AddSingleton<IHostingEnvironment, HostingEnvironment>()
             //..
            .BuildServiceProvider();

0 个答案:

没有答案