views:

21

answers:

2

Is there a way i can set AutoFac to use PropertiesAutowired(true) to be the default for all types being registered.

i.e. I dont want to use ".PropertiesAutowired(true)" all the time

var builder = new ContainerBuilder();
builder.RegisterType<Logger>()
    .PropertiesAutowired(true)
    .SingleInstance();
A: 

No, there isn't. Though, if you register types in bulk or by convention it will be easier, e.g. using builder.RegisterAssemblyTypes(..).

Update: Yes there is, see @Nicholas answer.

Peter Lillevold
As I expected. Thanks
Simon
+3  A: 

This can be done with a module, e.g.

class InjectPropertiesByDefaultModule : Autofac.Module {
    protected override void AttachToComponentRegistration(
        IComponentRegistration registration,
        IComponentRegistry registry) {
            registration.Activating += (s, e) => {
                e.Context.InjectProperties(e.Instance);
            };
    }
}

Then:

builder.RegisterModule<InjectPropertiesByDefaultModule>();

I think you might be misunderstanding the true paramerter to PropertiesAutowired - it determines how circular dependencies are supported and should probably remain false. To emulate the true setting you can attach to Activated instead of Activating above.

However, if at all possible, use constructor injection even for "optional" dependencies like your ILog. It leads to cleaner components (e.g. fields can be made readonly) and dependencies are more understandable (they're all in the constructor, and there's no guessing about the meaning of individual properties.)

Only consider using property injection when there are multiple configurations of the application and in some configurations the dependency will be truly absent.

Even in these cases, the "Null Object" pattern is usually a better fit.

Nicholas Blumhardt
Also - if you're integrating Log4Net, take a look at: http://code.google.com/p/autofac/wiki/Log4NetIntegration :)
Nicholas Blumhardt
Nic. in your code where does "e" come from?
Simon
Thanks Simon - should have been "registration" - fixed now.
Nicholas Blumhardt
Doh, nice one, we shouldn't underestimate the power of Autofac modules :) My ignorant answer is hereby modified.
Peter Lillevold
Nic. Ignore my question.
Simon