Dependency Injection issue : Unable to resolve service











up vote
-1
down vote

favorite












I'm trying to implement 3-tier concept in my ASP.NET Core MVC application and I'm quite struggling with DI.



Here's a quick representation of solution structure :




  • Business

  • Common


    • User



  • Data


    • AppDbContext



  • Web


    • Controllers

    • Views




Business, Common, Data and Web are 4 different projects referencing each other when necessary.



Problem is, when I try to access the AppDbContext inside controllers, I get this error :




InvalidOperationException: Unable to resolve service for type 'com.jds.chat.Data.AppDbContext' while attempting to activate 'com.jds.chat..Web.Controllers.CustomCriMessengerClientBotController'




The AppDbContext.cs in the Data project:



public class AppDbContext : DbContext
{
static string DbContextName = "AppDbConnectionString";

public DbSet<User> Users { get; set; }

public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}

public AppDbContext(): base()
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration
.GetConnectionString(DbContextName);
optionsBuilder.UseSqlServer(connectionString,
x => x.MigrationsAssembly("com.jds.chat..Data"));
}
}

public virtual void Commit()
{
base.SaveChanges();
}
}


The Container builder in the Data project:



public class AutoFacDataModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();

}
}


The controller in Web project :



private readonly AppDbContext _dbContext;

public ChatController(AppDbContext dbContext)
{
_dbContext = dbContext;
}

public IActionResult Index()
{
var users = _dbContext.Users.Where(u => u.IsInChat).ToList();
return View();
}


The startup.cs in web project :



public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime.
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent
// for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

var builder = new ContainerBuilder();

builder.RegisterModule(new AutofacBusinessModule());
builder.RegisterModule(new Cri.Module.Chatbot.
Business.AutofacBusinessModule());
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}


I'm missing something, but yet I don't see what...










share|improve this question
























  • Have you registered your DbContext with your DI container?
    – Jasen
    Nov 9 at 19:21










  • @Jasen Sorry, forgot inormation in original post. I edited to add the conatiner
    – j0w
    Nov 9 at 19:32















up vote
-1
down vote

favorite












I'm trying to implement 3-tier concept in my ASP.NET Core MVC application and I'm quite struggling with DI.



Here's a quick representation of solution structure :




  • Business

  • Common


    • User



  • Data


    • AppDbContext



  • Web


    • Controllers

    • Views




Business, Common, Data and Web are 4 different projects referencing each other when necessary.



Problem is, when I try to access the AppDbContext inside controllers, I get this error :




InvalidOperationException: Unable to resolve service for type 'com.jds.chat.Data.AppDbContext' while attempting to activate 'com.jds.chat..Web.Controllers.CustomCriMessengerClientBotController'




The AppDbContext.cs in the Data project:



public class AppDbContext : DbContext
{
static string DbContextName = "AppDbConnectionString";

public DbSet<User> Users { get; set; }

public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}

public AppDbContext(): base()
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration
.GetConnectionString(DbContextName);
optionsBuilder.UseSqlServer(connectionString,
x => x.MigrationsAssembly("com.jds.chat..Data"));
}
}

public virtual void Commit()
{
base.SaveChanges();
}
}


The Container builder in the Data project:



public class AutoFacDataModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();

}
}


The controller in Web project :



private readonly AppDbContext _dbContext;

public ChatController(AppDbContext dbContext)
{
_dbContext = dbContext;
}

public IActionResult Index()
{
var users = _dbContext.Users.Where(u => u.IsInChat).ToList();
return View();
}


The startup.cs in web project :



public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime.
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent
// for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

var builder = new ContainerBuilder();

builder.RegisterModule(new AutofacBusinessModule());
builder.RegisterModule(new Cri.Module.Chatbot.
Business.AutofacBusinessModule());
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}


I'm missing something, but yet I don't see what...










share|improve this question
























  • Have you registered your DbContext with your DI container?
    – Jasen
    Nov 9 at 19:21










  • @Jasen Sorry, forgot inormation in original post. I edited to add the conatiner
    – j0w
    Nov 9 at 19:32













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I'm trying to implement 3-tier concept in my ASP.NET Core MVC application and I'm quite struggling with DI.



Here's a quick representation of solution structure :




  • Business

  • Common


    • User



  • Data


    • AppDbContext



  • Web


    • Controllers

    • Views




Business, Common, Data and Web are 4 different projects referencing each other when necessary.



Problem is, when I try to access the AppDbContext inside controllers, I get this error :




InvalidOperationException: Unable to resolve service for type 'com.jds.chat.Data.AppDbContext' while attempting to activate 'com.jds.chat..Web.Controllers.CustomCriMessengerClientBotController'




The AppDbContext.cs in the Data project:



public class AppDbContext : DbContext
{
static string DbContextName = "AppDbConnectionString";

public DbSet<User> Users { get; set; }

public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}

public AppDbContext(): base()
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration
.GetConnectionString(DbContextName);
optionsBuilder.UseSqlServer(connectionString,
x => x.MigrationsAssembly("com.jds.chat..Data"));
}
}

public virtual void Commit()
{
base.SaveChanges();
}
}


The Container builder in the Data project:



public class AutoFacDataModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();

}
}


The controller in Web project :



private readonly AppDbContext _dbContext;

public ChatController(AppDbContext dbContext)
{
_dbContext = dbContext;
}

public IActionResult Index()
{
var users = _dbContext.Users.Where(u => u.IsInChat).ToList();
return View();
}


The startup.cs in web project :



public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime.
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent
// for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

var builder = new ContainerBuilder();

builder.RegisterModule(new AutofacBusinessModule());
builder.RegisterModule(new Cri.Module.Chatbot.
Business.AutofacBusinessModule());
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}


I'm missing something, but yet I don't see what...










share|improve this question















I'm trying to implement 3-tier concept in my ASP.NET Core MVC application and I'm quite struggling with DI.



Here's a quick representation of solution structure :




  • Business

  • Common


    • User



  • Data


    • AppDbContext



  • Web


    • Controllers

    • Views




Business, Common, Data and Web are 4 different projects referencing each other when necessary.



Problem is, when I try to access the AppDbContext inside controllers, I get this error :




InvalidOperationException: Unable to resolve service for type 'com.jds.chat.Data.AppDbContext' while attempting to activate 'com.jds.chat..Web.Controllers.CustomCriMessengerClientBotController'




The AppDbContext.cs in the Data project:



public class AppDbContext : DbContext
{
static string DbContextName = "AppDbConnectionString";

public DbSet<User> Users { get; set; }

public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}

public AppDbContext(): base()
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration
.GetConnectionString(DbContextName);
optionsBuilder.UseSqlServer(connectionString,
x => x.MigrationsAssembly("com.jds.chat..Data"));
}
}

public virtual void Commit()
{
base.SaveChanges();
}
}


The Container builder in the Data project:



public class AutoFacDataModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();

}
}


The controller in Web project :



private readonly AppDbContext _dbContext;

public ChatController(AppDbContext dbContext)
{
_dbContext = dbContext;
}

public IActionResult Index()
{
var users = _dbContext.Users.Where(u => u.IsInChat).ToList();
return View();
}


The startup.cs in web project :



public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime.
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent
// for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

var builder = new ContainerBuilder();

builder.RegisterModule(new AutofacBusinessModule());
builder.RegisterModule(new Cri.Module.Chatbot.
Business.AutofacBusinessModule());
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}


I'm missing something, but yet I don't see what...







asp.net-mvc asp.net-core dependency-injection






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 21:01

























asked Nov 9 at 19:08









j0w

699




699












  • Have you registered your DbContext with your DI container?
    – Jasen
    Nov 9 at 19:21










  • @Jasen Sorry, forgot inormation in original post. I edited to add the conatiner
    – j0w
    Nov 9 at 19:32


















  • Have you registered your DbContext with your DI container?
    – Jasen
    Nov 9 at 19:21










  • @Jasen Sorry, forgot inormation in original post. I edited to add the conatiner
    – j0w
    Nov 9 at 19:32
















Have you registered your DbContext with your DI container?
– Jasen
Nov 9 at 19:21




Have you registered your DbContext with your DI container?
– Jasen
Nov 9 at 19:21












@Jasen Sorry, forgot inormation in original post. I edited to add the conatiner
– j0w
Nov 9 at 19:32




@Jasen Sorry, forgot inormation in original post. I edited to add the conatiner
– j0w
Nov 9 at 19:32












1 Answer
1






active

oldest

votes

















up vote
0
down vote













You're registering the AppDbContext in the AutoFacDataModule, here:



public class AutoFacDataModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();
}
}


But you're not registering that module with Autofac with anywhere in ConfigureServices. You're registering two other modules:



builder.RegisterModule(new AutofacBusinessModule());
builder.RegisterModule(new Cri.Module.Chatbot.Business.AutofacBusinessModule());


But not the AutodacDataModule. You need to add something like:



builder.RegisterModule(new AutofacDataModule());





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53231908%2fdependency-injection-issue-unable-to-resolve-service%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    You're registering the AppDbContext in the AutoFacDataModule, here:



    public class AutoFacDataModule : Autofac.Module
    {
    protected override void Load(ContainerBuilder builder)
    {
    builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();
    }
    }


    But you're not registering that module with Autofac with anywhere in ConfigureServices. You're registering two other modules:



    builder.RegisterModule(new AutofacBusinessModule());
    builder.RegisterModule(new Cri.Module.Chatbot.Business.AutofacBusinessModule());


    But not the AutodacDataModule. You need to add something like:



    builder.RegisterModule(new AutofacDataModule());





    share|improve this answer



























      up vote
      0
      down vote













      You're registering the AppDbContext in the AutoFacDataModule, here:



      public class AutoFacDataModule : Autofac.Module
      {
      protected override void Load(ContainerBuilder builder)
      {
      builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();
      }
      }


      But you're not registering that module with Autofac with anywhere in ConfigureServices. You're registering two other modules:



      builder.RegisterModule(new AutofacBusinessModule());
      builder.RegisterModule(new Cri.Module.Chatbot.Business.AutofacBusinessModule());


      But not the AutodacDataModule. You need to add something like:



      builder.RegisterModule(new AutofacDataModule());





      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        You're registering the AppDbContext in the AutoFacDataModule, here:



        public class AutoFacDataModule : Autofac.Module
        {
        protected override void Load(ContainerBuilder builder)
        {
        builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();
        }
        }


        But you're not registering that module with Autofac with anywhere in ConfigureServices. You're registering two other modules:



        builder.RegisterModule(new AutofacBusinessModule());
        builder.RegisterModule(new Cri.Module.Chatbot.Business.AutofacBusinessModule());


        But not the AutodacDataModule. You need to add something like:



        builder.RegisterModule(new AutofacDataModule());





        share|improve this answer














        You're registering the AppDbContext in the AutoFacDataModule, here:



        public class AutoFacDataModule : Autofac.Module
        {
        protected override void Load(ContainerBuilder builder)
        {
        builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();
        }
        }


        But you're not registering that module with Autofac with anywhere in ConfigureServices. You're registering two other modules:



        builder.RegisterModule(new AutofacBusinessModule());
        builder.RegisterModule(new Cri.Module.Chatbot.Business.AutofacBusinessModule());


        But not the AutodacDataModule. You need to add something like:



        builder.RegisterModule(new AutofacDataModule());






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 9 at 21:28

























        answered Nov 9 at 21:23









        jmoerdyk

        4,51462838




        4,51462838






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53231908%2fdependency-injection-issue-unable-to-resolve-service%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Schultheiß

            Verwaltungsgliederung Dänemarks

            Liste der Kulturdenkmale in Wilsdruff