下午好
我最近开始尝试使用 Service Fabric 和 .NET Core。 我创建了一个无状态 Web API 并使用以下方法执行了一些 DI:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
var connString = Configuration.GetConnectionString("DefaultConnection");
services.AddScoped<FaxLogic>();
services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(connString));
}
通过上面的代码,我可以在我的 FaxLogic 类和 DbContext 类上使用构造函数注入(inject)(通过 FaxLogic):
private readonly FaxLogic _faxLogic;
public FaxController(
FaxLogic faxLogic)
{
_faxLogic = faxLogic;
}
private readonly ApplicationContext _context;
public FaxLogic(ApplicationContext context)
{
_context = context;
}
然后我创建了一个非 Web API 无状态服务。我希望能够像在我的 WebAPI 中一样访问我的 FaxLogic 和 DbContext,但在无状态服务的 RunAsync 方法中:
protected override async Task RunAsync(CancellationToken cancellationToken)
{
// TODO: Replace the following sample code with your own logic
// or remove this RunAsync override if it's not needed in your service.
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
ServiceEventSource.Current.ServiceMessage(this.Context, "Hello!");
// do db stuff here!
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
}
}
我想知道我会怎么做。我尝试使用 CreateServiceInstanceListeners() 方法和用于注册 ServiceRuntime 的 Program.cs 文件,但我似乎无法弄清楚!任何帮助将不胜感激。
最佳答案
这里已经回答了解决方案:Set up Dependency Injection on Service Fabric using default ASP.NET Core DI container
总而言之,您必须在创建无状态服务的新实例之前注册依赖项,然后创建一个工厂方法来解析依赖项:
即:
public static class Program
{
public static void Main(string[] args)
{
var provider = new ServiceCollection()
.AddLogging()
.AddSingleton<IFooService, FooService>()
.AddSingleton<IMonitor, MyMonitor>()
.BuildServiceProvider();
ServiceRuntime.RegisterServiceAsync("MyServiceType",
context => new MyService(context, provider.GetService<IMonitor>());
}).GetAwaiter().GetResult();
有关详细信息,请参阅链接的答案。
关于c# - 如何在 Service Fabric 中使用 .NET Core 的内置依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54696048/