I've been using the Autofac framework for the last couple of days and
have been unable to get property injection working within the MVC
application I'm developing. I've set Autofac up within the
Application_Start method, as per the instructions on the wiki, but
whenever I debug into my code, the property I'm trying to inject is
always null.
Here's my scenario:
I have a strongly typed view that is bound to a domain object called
Client, via a controller called AgentController. This object has an
IClientData property called DataProvider that resolves to an instance
of ClientData. What do I need to do to get the DataProvider property
to not be null? I'm using Autofac 1.4.5 at the moment but would like
to switch to 2, if I can get this working! I could use constructor
injection but would need to rethink the architecture and maybe make
use of the Controller Factory I've been reading about to register my
controller classes. Because the Client object is tied to the view, the
instance I get is provided to me by the MVC framework, hence it gets
instantiated with an empty constructor. Not yet sure how I'd get
around that one.
Here's the code in my Global.asax file. What have I missed/not done
correctly/misunderstood? I've seen the wiki page on Property Injection
but am none the wiser for reading it! Is it more straightforward to do
this using Autofac 2? I noticed that ActivatingHandler is no longer
present within version 2 - what's the equivalent technique?
/// <summary>
/// Starts the application.
/// </summary>
protected void Application_Start()
{
ContainerBuilder builder = RegisterDependencies();
AutofacControllerModule autofacControllerModule = new
AutofacControllerModule(Assembly.GetExecutingAssembly());
autofacControllerModule.ActivatingHandler +=
ActivatingHandler.InjectProperties;
builder.RegisterModule(autofacControllerModule);
containerProvider = new ContainerProvider(builder.Build());
ControllerBuilder.Current.SetControllerFactory(new
AutofacControllerFactory(this.ContainerProvider));
... other code omitted ...
}
/// <summary>
/// Registers the dependencies.
/// </summary>
/// <returns>A ContainerBuilder with the dependencies registered.</
returns>
private static ContainerBuilder RegisterDependencies()
{
ContainerBuilder builder = new ContainerBuilder();
builder.Register<AgentController>();
builder.Register<Model.Client>().OnActivating
(ActivatingHandler.InjectProperties);
builder.Register<ClientData>().As<IClientData>().OnActivating
(ActivatingHandler.InjectProperties);
return builder;
}
Thanks in advance for any help you can give me
Simon
--
You received this message because you are subscribed to the Google Groups "Autofac" group.
To post to this group, send email to aut...@googlegroups.com.
To unsubscribe from this group, send email to autofac+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/autofac?hl=en.