Search code examples
c#wpfdependenciesautofac

Autofac: Registering types with dependencies


I'm trying to register my WPF views with their corresponding viewmodels and avoid having to use code behind.

So far my code would look like this:

 builder.Register(c =>
    {
        PageA page = new PageA();
        page.DataContext = c.Resolve<PageAViewModel>;
        return page;
    });

    builder.Register(c =>
    {
        PageB page = new PageB();
        page.DataContext = c.Resolve<PageBViewModel>;
        return page;
    });

Is there are a more dynamic way to avoid having to write these lines for all views/pages? (if possible without using Service locator pattern).


Solution

  • You can create a generic method that will register your types :

    public static class RegistrationExtension
    {
    
        public static IRegistrationBuilder<TPage, ConcreteReflectionActivatorData, SingleRegistrationStyle> 
            RegisterPage<TPage, TViewModel>(this ContainerBuilder builder)
            where TPage : IPage
        {
            return builder.RegisterType<TPage>()
                          .OnActivated(e =>
                          {
                              e.Instance.DataContext = e.Context.Resolve<TViewModel>();
                          });
    
        }
    }
    

    and then register your pages like this :

    builder.RegisterPage<PageA, PageAViewModel>();