[RESOLVED]Managing DB Connection with Autofac

Hi

I am having a problem, up until now everything was fine, however I have a part which uses ajax, it looks through the html and every time it finds whats its looking for it, sends an ajax request to the controller, which then uses autofac to  connect to the
database and build a html partial which will be returned.

Now it works if it only finds 1 thing in the html, but as soon as it finds one it causes as error, which if down to autofac and the db connection being disposed from the first thing found.

I am a little lost and would appreciate some help, i have looked at the autofac site which seems a little unfinished and I am none the wiser.

I have tried the following;

builder.Register(c => new MyContext()).As<IUnitOfWork>().SingleInstance();

builder.Register(c => new MyContext()).As<IUnitOfWork>().ExternallyOwned();

Just realised that in the part I have an error I am using MVC’s DependencyResolver.Current.GetService, I am not having this issue with Autocompletes which doesn’t use the DependencyResolver

Any information would be appriciated.

EnenDaveyBoy

Now it works if it only finds 1 thing in the html, but as soon as it finds one it causes as error, which if down to autofac and the db connection being disposed from the first thing found

EnenDaveyBoy

Just realised that in the part I have an error I am using MVC’s DependencyResolver.Current.GetService, I am not having this issue with Autocompletes which doesn’t use the DependencyResolver

Please show error and code.

ignatandrei

EnenDaveyBoy

Now it works if it only finds 1 thing in the html, but as soon as it finds one it causes as error, which if down to autofac and the db connection being disposed from the first thing found

EnenDaveyBoy

Just realised that in the part I have an error I am using MVC’s DependencyResolver.Current.GetService, I am not having this issue with Autocompletes which doesn’t use the DependencyResolver

Please show error and code.

Hi

The error I am getting is

An error occurred while executing the command definition. See the inner exception for details.

Since its an ajax call I have no idea how to get more detail, since the browser only has an alert popup with "error" in it, the error occurs on this

public StockSupplier GetById(int id, int companyId)
        {

            return _repository.Table
                                .Where(t => t.Id == id && t.CompanyId == companyId)
                                .FirstOrDefault();

        }

everything runs fine when the code executes the first time, its only when the code hits the above code the second time that is has an error.

This is how I get to the code above

private static ISupplierService _supplierService = DependencyResolver.Current.GetService<ISupplierService>();
public static CreateAndUpdateStockOrderViewModel BlankViewModel(this CreateAndUpdateStockOrderViewModel model, int supplierId)
        {
            model.AddEssentials();

            //Add Supplier Info

            var supplier = _supplierService.GetById(supplierId, model.CompanyId);

            model.SupplierName = supplier.Name;
            model.SupplierId = supplier.Id;

            model.OrderDate = DateTime.Now;
            model.DeliveryDate = DateTime.Now;

            return model;
        }

If you need to ajax call or anything else please let me know.

Sorry also add my DI configuration:

public static void RegisterDependencies()
        {
            #region DI

            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);


            //Register Context
            //builder.Register(c => new MyContext()).As<IUnitOfWork>().InstancePerLifetimeScope();
            builder.Register(c => new MyContext()).As<IUnitOfWork>().SingleInstance();

            //Repositories
            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerHttpRequest();
            
     //Service Layer

            builder.RegisterType<CompanyLocationService>().As<ICompanyLocationService>().InstancePerHttpRequest();
            builder.RegisterType<CompanyService>().As<ICompanyService>().InstancePerHttpRequest();
            builder.RegisterType<ResourceService>().As<IResourceService>().InstancePerHttpRequest();
            builder.RegisterType<LocationService>().As<ILocationService>().InstancePerHttpRequest();
            builder.RegisterType<WebAccountService>().As<IWebAccountService>().InstancePerHttpRequest();
            builder.RegisterType<TaxService>().As<ITaxService>().InstancePerHttpRequest();
            builder.RegisterType<StockService>().As<IStockService>().InstancePerHttpRequest();
            builder.RegisterType<StockFeatureService>().As<IStockFeatureService>().InstancePerHttpRequest();
            builder.RegisterType<StockBrandService>().As<IStockBrandService>().InstancePerHttpRequest();
            builder.RegisterType<StockTitleOptionService>().As<IStockTitleOptionService>().InstancePerHttpRequest();
            builder.RegisterType<StockOptionTypeService>().As<IStockOptionTypeService>().InstancePerHttpRequest();
            builder.RegisterType<ProductService>().As<IProductService>().InstancePerHttpRequest();
            builder.RegisterType<WebsiteService>().As<IWebsiteService>().InstancePerHttpRequest();
            builder.RegisterType<SettingService>().As<ISettingService>().InstancePerHttpRequest();
            builder.RegisterType<SizeChartService>().As<ISizeChartService>().InstancePerHttpRequest();
            builder.RegisterType<StockSupplierService>().As<IStockSupplierService>().InstancePerHttpRequest();
            builder.RegisterType<StockOrderService>().As<IStockOrderService>().InstancePerHttpRequest();
            builder.RegisterType<WebsiteGroupService>().As<IWebsiteGroupService>().InstancePerHttpRequest();
            builder.RegisterType<WebsiteSectionService>().As<IWebsiteSectionService>().InstancePerHttpRequest();
            builder.RegisterType<WebsiteCategoryService>().As<IWebsiteCategoryService>().InstancePerHttpRequest();
            builder.RegisterType<IPriceGroupService>().As<IPriceGroupService>().InstancePerHttpRequest();
            builder.RegisterType<ForumService>().As<IForumService>().InstancePerHttpRequest();
            builder.RegisterType<ArticleService>().As<IArticleService>().InstancePerHttpRequest();
            builder.RegisterType<FileService>().As<IFileService>().InstancePerHttpRequest();
            builder.RegisterType<EmployeeService>().As<IEmployeeService>().InstancePerHttpRequest();
            builder.RegisterType<PriceGroupService>().As<IPriceGroupService>().InstancePerHttpRequest();
            //builder.RegisterType<TeamService>().As<ITeamService>().InstancePerHttpRequest();

            //builder.RegisterType<NotificationService>().As<INotificationService>().InstancePerHttpRequest();
            //builder.RegisterType<ClanService>().As<IClanService>().InstancePerHttpRequest();
            //builder.RegisterType<EmailService>().As<IEmailService>().InstancePerHttpRequest();
            //builder.RegisterType<FileManagerService>().As<IFileManagerService>().InstancePerHttpRequest();
            //builder.RegisterType<ForumService>().As<IForumService>().InstancePerHttpRequest();
            //builder.RegisterType<ArticleService>().As<IArticleService>().InstancePerHttpRequest();
            ////builder.RegisterType<MatchService>().As<IMatchService>().InstancePerHttpRequest();
            //builder.RegisterType<PersonService>().As<IPersonService>().InstancePerDependency();
            //builder.RegisterType<ChatService>().As<IChatService>().InstancePerDependency();
            //builder.RegisterType<SubscriptionService>().As<ISubscriptionService>().InstancePerHttpRequest();
            //builder.RegisterType<HubService>().As<IHubService>().InstancePerHttpRequest();
            //builder.RegisterType<ChatHub>().InstancePerLifetimeScope(); 

            //builder.RegisterType<ChatHub>().ExternallyOwned();
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            // Create the depenedency resolver.
            //var resolver = new AutofacDependencyResolver(container);

            // Configure SignalR with the dependency resolver.
            //GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);


            //GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);
            //RouteTable.Routes.MapHubs();
            // See IContainer for definition of the container variable


            #endregion
        }

EnenDaveyBoy

The error I am getting is

An error occurred while executing the command definition. See the inner exception for details.

and the inner exception message?

How do I get it? Since its an ajax call I don’t get the error message on the screen in the same way you get a error normally

I think I have it:

HResult = -2146232004

InnerException = {"There is already an open DataReader associated with this Command which must be closed first."}

Message = "An error occurred while executing the command definition. See the inner exception for details."

Source = "EntityFramework"

StackTrace = "   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)rn   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectCo…

I hope thats right

make

 _repository 

local to ajax call – and call dispose.

Do not re-use on all controller 

Sorry I need more info, I am not sure how or what to do.

(I also thought that autofac would deal with the disposal)

To link to an example would be appriciated

Right after a little googling, I now understand what you mean, however I repository is behind a service layer, so would I have manually build the repository and the service layer using the repository.

is there another option, just building a connection manager or something that would mean it does it for me.

Make the repository transient – require a new instance every time. And put the _repository variable in the action.

I remove Iqueryable from the service layer and its now fixed, thanks for the help.

Leave a Reply