带有.NET 6控制台应用程序和ServiceCollection的AutoFac
我正在尝试使用 serviceCollection
在控制台应用程序中填充 serviceCollection
。我阅读文档但没有针对我的特定情况的指南。
我面临的问题是,当我使用接口类型询问时,构建的ServiceCollection找不到实现。我认为AutoFac并未填充 serviecollection
。
program.cs
using System.Reflection;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Core.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
var serviceProvider = new ServiceCollection()
.AddLogging(cfg => cfg.AddConsole())
.Configure<LoggerFilterOptions>(cfg => cfg.MinLevel = LogLevel.Information)
.AddAutofac(cfg =>
{
cfg.RegisterAssemblyTypes(Assembly.Load("Core")).AsImplementedInterfaces();
})
.BuildServiceProvider();
var markDownParser = serviceProvider.GetRequiredService<IMarkDownParser>();
markdownparser.cs
namespace Core;
public class MarkDownParser : IMarkDownParser
{
private readonly ILogger<MarkDownParser> _logger;
public MarkDownParser(ILogger<MarkDownParser> logger)
{
_logger = logger;
}
}
imarkdownparser.cs
namespace Core.Interfaces;
public interface IMarkDownParser
{
object Parse(string text);
}
错误:
Unhandled exception. System.InvalidOperationException: No service for type 'Core.Interfaces.IMarkDownParser' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Program.<Main>$(String[] args) in /home/amir/RiderProjects/git-blog/ConsoleApp/Program.cs:line 20
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为问题在
addautofac
扩展方法仅在 asp.net core 1.1-2.2 中支持。如果我们想将AutoFac作为DI容器,则有一个示例可以谈论 netcore快速启动
一旦您注册了ServiceCollection中的所有内容并调用
pupulate
将这些注册通过containerbuilder
final final创建 AUTOFAC一个新的
autofacserviceProvider
使DI容器可以使用。I think the problem is on
AddAutofac
extension method only supports during ASP.NET Core 1.1 - 2.2.if we want to use autofac to be the DI Container, there is an example to talk about netcore quick-start
Once you've registered everything in the ServiceCollection and call
Populate
to bring those registrations into Autofac byContainerBuilder
Final, Creating a new
AutofacServiceProvider
makes the DI container and we can use that.文档说仅使用
addautofac
仅适用于pre-asp.net 3.0托管。这对ASP.NET Core 3.0+或通用托管不起作用。
因为
.net 6
已被标记。我认为该框架是问题的一部分。这是我的实施以及一些可以帮助的文档。
https://autofac.readthedocs.io/en/latest/latest/integration/aspnetegration/aspnetcore.html
//
Documentation says that only use
AddAutofac
ONLY FOR PRE-ASP.NET 3.0 HOSTING. THIS WON'T WORK FOR ASP.NET CORE 3.0+ OR GENERIC HOSTING.
Since
.net 6
has been tagged. I'm thinking the framework is part of the issue.Here is my implementation as well as some documentation to help.
https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html
// Main
// Core Assembly