[英]AutoFac SingleInstance with streamreader
How should i register/configure the container, so that the filereader doesn't have to keep reading the file for every request (which is actually a certificate), the cert doesn't change during runtime 我应该如何注册/配置容器,以便文件读取器不必为每个请求(实际上是证书)继续读取文件,证书在运行时不会更改
Registration of service into container 将服务注册到容器中
public static void AddMyService(this ContainerBuilder builder)
{
builder.Register(context =>
{
var configuration = context.Resolve<IConfiguration>();
var options = configuration.GetOptions<ServiceOptions>(SectionName);
return options;
}).SingleInstance();
builder.RegisterType<MyService>().As<IMyService>()
.InstancePerDependency();
}
Implementation of service 实施服务
public CustomStuff DoCustomStuff(...)
{
...
using (var fileStream = File.OpenRead(_options.SomePath))
{
...
}
}
A couple of options here but personally I'd just create a new class to hold the data you're reading, since it makes the registrations a bit clearer. 这里有几个选项,但我个人只是创建一个新类来保存您正在读取的数据,因为它使注册更加清晰。 Looks like you don't need to keep the file stream open, you can just read once and forget about it. 看起来您不需要保持文件流打开,只需阅读一次就可以了。
public class Certificate
{
public Certificate(string value)
{
Value = value;
}
public string Value { get; }
}
private static string ReadFile(ServiceOptions options)
{
return File.ReadAllText(options.SomePath);
}
Then you can just register that as a singleton and inject it into your MyService implementation: 然后,您可以将其注册为单例并将其注入MyService实现中:
builder.Register(context =>
{
var options = context.Resolve<ServiceOptions>();
var data = ReadFile(options);
return new Certificate(options.SomePath);
})
.As<Certificate>()
.SingleInstance();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.