c# - No service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' has been registered -


i have problem when want fire add-migration command asp mvc core 2 project.

no service type 'microsoft.aspnetcore.hosting.ihostingenvironment' has been registered.

here startup.cs:

public class startup {     public startup(iconfiguration configuration)     {         configuration = configuration;     }      public iconfiguration configuration { get; set; }      public void configureservices(iservicecollection services)     {         services.adddbcontextpool<samplearchcontext>((serviceprovider, optionsbuilder) =>         {             optionsbuilder.useinternalserviceprovider(serviceprovider); // it's added access services dbcontext, remove if using normal `adddbcontext` , normal constructor dependency injection.         });          services.addmvc(options =>         {             options.allowemptyinputinbodymodelbinding = true;         }).addjsonoptions(jsonoptions =>         {             jsonoptions.serializersettings.nullvaluehandling = newtonsoft.json.nullvaluehandling.ignore;         });     }      public void configure(         iloggerfactory loggerfactory,         iapplicationbuilder app,         ihostingenvironment env)     {          if (env.isdevelopment())         {             var builder = new configurationbuilder()              .setbasepath(env.contentrootpath)              .addjsonfile("appsettings.json", optional: true, reloadonchange: true)              .addjsonfile($"appsettings.{env.environmentname}.json", optional: true)              .addenvironmentvariables();             configuration = builder.build();              app.usedeveloperexceptionpage();             app.usebrowserlink();         }         else         {             app.useexceptionhandler("/home/error");         }          app.usestaticfiles();          app.usemvc(routes =>         {             routes.maproute(                 name: "default",                 template: "{controller=home}/{action=index}/{id?}");         });         app.usefileserver(new fileserveroptions         {             fileprovider = new physicalfileprovider(path.combine(directory.getcurrentdirectory(), "bower_components")),             requestpath = "/bower_components",             enabledirectorybrowsing = false         });                 } } 

program.cs:

public class program {     public static void main(string[] args)     {         var host = new webhostbuilder()             .usekestrel()             .usecontentroot(directory.getcurrentdirectory())             .configureappconfiguration((hostingcontext, config) =>             {                 var env = hostingcontext.hostingenvironment;                 config.setbasepath(env.contentrootpath);                 config.addinmemorycollection(new[]                        {                          new keyvaluepair<string,string>("the-key", "the-value")                        })                        .addjsonfile("appsettings.json", reloadonchange: true, optional: false)                        .addjsonfile($"appsettings.{env}.json", optional: true)                        .addenvironmentvariables();             })             .configurelogging((hostingcontext, logging) =>             {                 logging.adddebug();                 logging.addconsole();             })             .useiisintegration()             .usedefaultserviceprovider((context, options) =>             {                 options.validatescopes = context.hostingenvironment.isdevelopment();             })             .usestartup<startup>()             .build();          host.run();     } } 

context:

public interface icontext {     dbset<person> persons { get; set; }     dbset<country> countries { get; set; }     dbset<tentity> set<tentity>() tentity : class;     entityentry<tentity> entry<tentity>(tentity entity) tentity : class;     int savechanges(); } public class samplearchcontext : dbcontext, icontext {     public samplearchcontext(dbcontextoptions<samplearchcontext> options)         : base(options)     { }     public dbset<person> persons { get; set; }     public dbset<country> countries { get; set; }     protected override void onmodelcreating(modelbuilder modelbuilder)     {         base.onmodelcreating(modelbuilder);         modelbuilder.entity<country>(build =>         {             build.property(category => category.name).hasmaxlength(450).isrequired();         });     }     public override int savechanges()     {         var modifiedentries = changetracker.entries()             .where(x => x.entity iauditableentity                 && (x.state == entitystate.added || x.state == entitystate.modified));          foreach (var entry in modifiedentries)         {             iauditableentity entity = entry.entity iauditableentity;             if (entity != null)             {                 string identityname = thread.currentprincipal.identity.name;                 datetime = datetime.utcnow;                  if (entry.state == entitystate.added)                 {                     entity.createdby = identityname;                     entity.createddate = now;                 }                 else                 {                     base.entry(entity).property(x => x.createdby).ismodified = false;                     base.entry(entity).property(x => x.createddate).ismodified = false;                 }                 entity.updatedby = identityname;                 entity.updateddate = now;             }         }          return base.savechanges();     } } public class designtimedbcontextfactory : idesigntimedbcontextfactory<samplearchcontext> {         public samplearchcontext createdbcontext(string[] args)     {         var service = new servicecollection();         service.addoptions();         //service.addscoped<ihostingenvironment, customhostingenvironment>();         service.addsingleton<iloggerfactory, loggerfactory>();         var serviceprovider = service.buildserviceprovider();         var hostingenvirement = serviceprovider.getrequiredservice<ihostingenvironment>();         iconfigurationroot configuration = new configurationbuilder()             .addjsonfile("appsettings.json", optional: true, reloadonchange: true)            .setbasepath(basepath: hostingenvirement.contentrootpath)            //.setbasepath(directory.getcurrentdirectory())             .build();         service.addsingleton(provider => configuration);         serviceprovider = service.buildserviceprovider();          var builder = new dbcontextoptionsbuilder<samplearchcontext>();         var connectionstring = configuration.getconnectionstring("appdbcontextconnection");         builder.usesqlserver(connectionstring);         return new samplearchcontext(builder.options);     } } 

and here appsetting.json :

appsetting.json :

{   "connectionstrings": {     "appdbcontextconnection": "server=localhost; database=coredbname;trusted_connection=true; multipleactiveresultsets=true"   },   "logging": {     "includescopes": false,     "loglevel": {       "default": "warning"     }   } } 

i've searched lot couldn't found solution problem, how can fix it?

there's new application pattern in asp.net core 2. see migrating asp.net core 1.x asp.net core 2.0 details.

ef core no longer attempts directly invoke startup.configureservices(). in version 2.0, static program.buildwebhost() method , application services that.

to adopt new pattern, update program class this.

public class program {     public static iwebhost buildwebhost(string[] args)     {         var host = new webhostbuilder()             .usekestrel()             .usecontentroot(directory.getcurrentdirectory())             .configureappconfiguration((hostingcontext, config) =>             {                 var env = hostingcontext.hostingenvironment;                 config.setbasepath(env.contentrootpath);                 config.addinmemorycollection(new[]                        {                          new keyvaluepair<string,string>("the-key", "the-value")                        })                        .addjsonfile("appsettings.json", reloadonchange: true, optional: false)                        .addjsonfile($"appsettings.{env}.json", optional: true)                        .addenvironmentvariables();             })             .configurelogging((hostingcontext, logging) =>             {                 logging.adddebug();                 logging.addconsole();             })             .useiisintegration()             .usedefaultserviceprovider((context, options) =>             {                 options.validatescopes = context.hostingenvironment.isdevelopment();             })             .usestartup<startup>()             .build();          return host;     }      public static void main(string[] args)     {         buildwebhost(args).run();     } } 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -