简体   繁体   中英

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:

builder.Register(context =>
    {
        var options = context.Resolve<ServiceOptions>();
        var data = ReadFile(options);
        return new Certificate(options.SomePath);
    })
    .As<Certificate>()
    .SingleInstance();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM