Autofac object lifetime based on an event

Asked at 2016-12-30 09:09:42Z
  • 5 Subscribers
  • 114 Views
1

Consider below code in ASP.NET Core

public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);
        services.AddMvc();
        var builder = new ContainerBuilder();

        var loader = new LoadEngine<IContract>(@"DIRECTORY PATH") // works based on FileSystemWatcher and have ConcurrentDictionary as repository so can return latest types.
            .EnableHotPlug()
            .Build();

        var type = loader.GetInstances().FirstOrDefault().GetType(); // First Time
        builder.RegisterType(type).As<IContract>(); // First RegisterType

        loader.OnChange += () => // LoadEngine detect some changes in plugin directory so fire OnChange
        {
            type = loader.GetInstances().FirstOrDefault().GetType(); // Get latest instance from LoadEngine
            builder.RegisterType(type).As<IContract>(); // Register again in Autofac Container
        };

        builder.Populate(services);
        var container = this.ApplicationContainer = builder.Build();
        return new AutofacServiceProvider(this.ApplicationContainer);
    }

I wrote a LoadEngine based on FileSystemWatcher when a plugin (.dll) created/deleted/updated in that directory reload types into memory and provide new instance so this library have OnChange event

I want to have instance`s life-scope based on an event when event call Autofac reinstantiation that object.

Now first Resigter type is OK but on event despite of existing a new type Autofac send old type to controllers


0 answers in total

Answer this questsion