Set AutoFac to use PropertiesAutowired(true) as default?

天涯浪子 提交于 2019-12-07 18:12:34

问题


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();

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3384812/set-autofac-to-use-propertiesautowiredtrue-as-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!