简体   繁体   中英

Is worth avoiding newing up services in autofac container?

I'm trying to use autofac in a console application that uses some services inside a class library project.

My container config is something like this

public static IContainer Configure()
{
    var builder = new ContainerBuilder();

    builder.RegisterType<DateService>().As<IDateService>();

    builder.Register(paramService => new ParamService(paramService.Resolve<IDateService>()).As<IParamService>();

    return builder.Build();
}

But in the console app I'm not actually using the DateService for anything (ie it's only usage is for being the parameter of the newed ParamService in the container) so I wonder if it's worth doing that or would be just enough to do

public static IContainer Configure()
{
    var builder = new ContainerBuilder();

    builder.Register(paramService => new ParamService(new DateService()).As<IParamService>();

    return builder.Build();
} 

Is there any downside for that I can't think of?

It wouldn't be a big deal but in the real scenario I would need to register different things for the same interface and other relatively more complex scenarios so I think if there's nothing wrong with newing up the parameters I would go for it

Thanks

One downside of directly instantiating a service would be that other registrations wouldn't be able to override the implementation of IDateService - they'd have to change an unrelated registration. If your app gets big enough and you start splitting registrations into modules, that restriction may be unclear and folks may wonder why the IDateService everywhere else is the one they registered but it's not properly getting injected in this one instance.

Another downside would be if DateService is IDisposable - Autofac will track disposables and clean them up for you. In this case, you'd need to dispose of the DateService yourself.

The benefit of doing the direct instantiation is that it's technically faster - you're not going through the layers of Autofac to end up with new DateService() .

There is no recommendation one way or the other - you'll need to choose based on your application's needs.

To build upon Travis's answer, registering DateService separately also allows you to simplify your registration of ParamService to:

builder.RegisterType<ParamService>().As<IParamService>();

I prefer this syntax over the original because in the event that ParamService is modified to require an addition constructor parameter, its Autofac registration remains unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM