Jarvis Bot
Jarvis Bot

Reputation: 491

Autofac registration methodology and differences

Is there any difference between

builder.RegisterModule(new XYZModule());

and

builder.RegisterModule<XYZDataModule>();

???

Upvotes: 1

Views: 118

Answers (1)

nemesv
nemesv

Reputation: 139758

There is no difference: internally the builder.RegisterModule<XYZDataModule>(); is implemented like this:

public static void RegisterModule<TModule>(this ContainerBuilder builder) 
    where TModule : IModule, new()
{
    Autofac.RegistrationExtensions.RegisterModule(builder, (IModule) new TModule());
}

so the generic method is calling the non generic version.

Providing two methods for the same thing is mainly for convenience and preference reasons but this is a general practice in .net to provide a non generic version of the generic methods.

And usually there is a small difference in the usage:

If you know your module's type compilation time and your module does have a defualt contructor use the generic method (which is less character to type):

builder.RegisterModule<XYZModule>();

or if you don't know the module's type complication type or your module does not have a default constructor then use the other overload:

builder.RegisterModule(new XYZModule());

So as a general guideline: use the generic version if you know the type and use the non generic version if you don't know the type at the time of the compilation (of course you can create generic methods/classes also during run-time with reflection but that is a different story).

Upvotes: 2

Related Questions