Winetradr
Winetradr

Reputation: 141

Autofac: Get constructor parameter after resolve (OnActivated/OnActivating)

I have the following structure:

class SomeViewModel
{
    public SomeViewModel(SomeService service)
    {
        service.SetViewModel(this); // <- Move this call to Autofac
    }
}

class SomeService
{
    public void SetViewModel(object viewModel) 
    {
        //...
    }
}

Instead of manually calling service.SetViewModel in every ViewModel, I want to move this call to the IoC Container (Autofac). I've tried using OnActivated but there are no parameters available:

builder.Register<SomeViewModel>
    .AsSelf()
    .OnActivated(e =>
        {
            var service = e.Parameters
                .OfType<SomeService>()
                .FirstOrDefault(); // <- There are no parameters
            service.SetViewModel(e.Instance);
        });

Is it possible to move the call service.SetViewModel(this); in the SomeViewModel constructor into some kind of Autofac registration?

Upvotes: 0

Views: 231

Answers (1)

Alexander Leonov
Alexander Leonov

Reputation: 4794

I agree with @Steven. But even if we set this apart, what if there are several view models sharing the same service? Which one will get in the service - "last wins"? You'd want to think through this design one more time.

Now that you've been warned... Your solution could be following:

        ...
        builder.Register(s => CreateViewModel(s, svc => new SomeViewModel(svc))).AsSelf();
    }

    private T CreateViewModel<T>(IComponentContext ctx, Func<SomeService, T> createInstance) {
        var svc = ctx.Resolve<SomeService>();
        var instance = createInstance(svc);
        svc.SetViewModel(instance);
        return instance;
    }

Upvotes: 1

Related Questions