[英]How to create a singleton of a custom class and inject it other classes in .Net core 2.0? 'No service for type 'Services' has been registered.'?
I have a class in a .Net core 2.0 console application. 我在.Net core 2.0控制台应用程序中有一个类。 The class provides data service and will be used by the Main class. 该类提供数据服务,并将由Main类使用。 So a singleton of the class will be created for DI. 因此,将为DI创建该类的一个单例。
public class Services
{
private readonly DbContext _context;
public Services(DbContext context)
{
_context = context;
}
public IEnumerable<Items> GetList(string region)
{
return _context.Items;
}
}
The following code is in Program
class. 下面的代码在Program
类中。
var services = new ServiceCollection();
services.AddTransient<Main>(); // With constructor of public Main(Services service)
var serviceProvider = services.BuildServiceProvider();
....
services.AddDbContext<DbContext>(o => o.UseSqlServer(defaultConn));
services.AddSingleton<Services>();
var s = serviceProvider.GetRequiredService<Services>(); // Error
services.AddSingleton(s);
However, the second to the last line got the error of 但是,倒数第二行的错误是
'No service for type 'Services' has been registered.' “没有注册类型为“服务”的服务。”
? ?
The Main
class will need to access a singleton of Services
using DI. Main
类将需要使用DI访问单个Services
。
Once the service provider is built, it will not have knowledge of any additional services added to the service collection. 构建服务提供者后,它将不了解添加到服务集合中的任何其他服务。 Only build the provider once all the types have been added. 添加所有类型后,才构建提供程序。
var services = new ServiceCollection();
services.AddTransient<Main>(); // With constructor of public Main(Services service)
//....
services.AddDbContext<DbContext>(o => o.UseSqlServer(defaultConn));
services.AddSingleton<Services>();
var serviceProvider = services.BuildServiceProvider();
var s = serviceProvider.GetRequiredService<Services>(); // Should work now
When Main
is resolved the singleton will be injected 解决Main
,将注入单例
var main = serviceProvider.GetService<Main>(); //will include singleton Service
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.