Putting Autofac Properties in a Base Class

I am working on a Windows Phone 8.1 application and I have a base class with a public property.

public class ViewModelBase
{
   public ISomeClass MyProp {get;set;}
}

      

My derived class looks like this

public class MainViewModel : ViewModelBase
{
    private readonly INavigation _navigation;
    public MainViewModel(INavigation navigation)
    {
        _navigation = navigation;
    }
}

      

In my application.

 var builder = new ContainerBuilder();
 builder.RegisterType<Navigation>().As<INavigation>();
 builder.RegisterType<SomeClass>().As<ISomeClass>();
 builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());

      

When the MainViewModel is created, my initialization is allowed, but MyProp is NULL. I tried

builder.Register(c => new ViewModelBase { MyProp = c.Resolve<ISomeClass>() });

builder.Register(c => new ViewModelBase()).OnActivated(e => e.Instance.MyProp = e.Context.Resolve<ISomeClass>());

builder.RegisterType<ViewModelBase>().PropertiesAutowired();

      

but none of this works!

The solution is posted here http://bling.github.io/blog/2009/09/07/member-injection-module-for-autofac/

works but I don't like it :)

I don't want to use constructor injection in this case.

Thank.

+3


source to share


2 answers


You need to make sure that your viewmodel class is MainViewModel

registered with the property injection. Currently everything you have registered with introducing properties ViewModelBase

, but think about what you allow. You will never allow ViewModelBase

, you will allow MainViewModel

s. Thus, this is what needs to be registered with the container.

Try:



builder.RegisterType<MainViewModel>().PropertiesAutowired();

      

+6


source


This will load all the classes that inherit ViewModelBase

and only introduce the specific properties you want. In most cases, you don't want other properties on the child class to be introduced.



builder.RegisterAssemblyTypes( GetType().Assembly )
    .AssignableTo<ViewModelBase>()
    .OnActivated( args =>
    {
        var viewModel = args.Instance as ViewModelBase;
        if( viewModel != null )
        {
            viewModel.MyProp = args.Context.Resolve<ISomeClass>();
        }
    } );

      

+6


source







All Articles