I'm working with AutoFac to do some DI. I think I've got a decent grip on things, but just ran into a question I had with my code and thought I'd check:
public class AutofacRegistrations
{
public static void RegisterAndSetResolver()
{
// Create the container builder.
var containerBuilder = new ContainerBuilder();
// Register the Web API controllers.
containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// Only generate one SessionFactory ever because it is expensive.
containerBuilder.Register(x => new NHibernateConfiguration().Configure().BuildSessionFactory()).SingleInstance();
// Everything else wants an instance of Session per HTTP request, so indicate that:
containerBuilder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).InstancePerApiRequest();
containerBuilder.Register(x => LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType)).InstancePerApiRequest();
// TODO: I don't THINK I should actually be making a DAO factory per API request. I think the whole point of a Factory is to make them once.
containerBuilder.RegisterType<NHibernateDaoFactory>().As<IDaoFactory>().InstancePerApiRequest();
containerBuilder.RegisterType<StreamusManagerFactory>().As<IManagerFactory>().InstancePerApiRequest();
// Build the container.
ILifetimeScope container = containerBuilder.Build();
// Create the depenedency resolver.
var dependencyResolver = new AutofacWebApiDependencyResolver(container);
// Configure Web API with the dependency resolver.
GlobalConfiguration.Configuration.DependencyResolver = dependencyResolver;
}
}
You can see that I am registering an NHibernateDaoFactory
and a StreamusManagerFactory
as InstancePerApiRequest
. This doesn't feel right to me because I think creating a Factory is supposed to be a relatively expensive endeavour and they should probably be .SingleInstance()
similiar to the ISessionFactory
.
However, my NHibernateDaoFactory has a dependency on Session:
...
public NHibernateDaoFactory(ISession session)
{
if (session == null) throw new NullReferenceException("session");
Session = session;
}
public IErrorDao GetErrorDao()
{
return ErrorDao ?? (ErrorDao = new ErrorDao(Session));
}
....
and my ManagerFactory has a dependency on the DaoFactory:
...
public StreamusManagerFactory(ILog logger, IDaoFactory daoFactory)
{
if (logger == null) throw new NullReferenceException("logger");
if (daoFactory == null) throw new NullReferenceException("daoFactory");
Logger = logger;
DaoFactory = daoFactory;
}
public IErrorManager GetErrorManager()
{
return ErrorManager ?? (ErrorManager = new ErrorManager(Logger, DaoFactory.GetErrorDao()));
}
...
This leaves me having to create new factories per request. Is this correct?