Question

I'm building an MVC5 web app connecting to a MS SQL 2008 database, so that the users can search and make changes to data stored there. I've looked at a bunch of autofac tutorials and examples, but can't seem to make any of them work.

I'm assuming my autofac configuration is the problem, because when I run the app it says my model is null. Which I think means the autofac is not connecting to the datbase.

So, in my global.asax.cs file I have the following:

protected void Application_Start()
    {
        #region Autofac
        // Register Controllers
        var builder = new ContainerBuilder();
        builder.RegisterControllers(typeof(MvcApplication).Assembly); //all controllers in assembly at once ?            
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterFilterProvider();

        // Set the Dependency Resolver
        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        // Register Model Binders
        builder.RegisterModelBinders(typeof(MvcApplication).Assembly); //all binders in assembly at once ?
        builder.RegisterModelBinderProvider();

        // Register Modules
        builder.RegisterModule<PersistenceModule>();           

        #endregion

        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);


    }

I have a hibernate.cfg.xml file as

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="connection.connection_string">Data Source=DEVSRV\SQLSERVER;Initial Catalog=tipdemo;Persist Security Info=True;User ID=admin;Password=***********</property>
      <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
      <!--<mapping assembly="NHibernateTest"/> -->
    </session-factory>
  </hibernate-configuration>
</configuration>

And my PersistenceModule class is:

public class PersistenceModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            if (builder == null)
                throw new ArgumentException("builder", "builder is null");

            base.Load(builder);
        }


        private ISessionFactory ConfigureDB()
        {
            Configuration cfg = new Configuration().Configure(System.Web.HttpContext.Current.Server.MapPath("~/Config/hibernate.cfg.xml"));
            cfg.AddAssembly(typeof(Domain.General.Project).Assembly);
            return cfg.BuildSessionFactory();
        }
    }
Was it helpful?

Solution

You can't register things in the container after it's built.

On line 11 in the sample for Application_Start you're building the container, but then after you set the DependencyResolver you're registering more stuff with the ContainerBuilder. You can't do that - you have to register everything first, then build the container as the last thing you do.

That's why it's never entering your PersistenceModule - you've already built the container, so it's not actually getting registered.

If, for some reason, you need to add registrations to an already-built container, you need to create an all new ContainerBuilder and call builder.Update(container). However, I strongly recommend you just reorder things so the container is built last rather than go the Update route if possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top