Windows Service with .NET 6 not running with WebApplication builder - windows-services

I am having the following error when trying to create a windows service:
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NotSupportedException: The content root changed from "C:\WINDOWS\system32" to "C:\foo\foo\publish". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.
My builder:
var builder = WebApplication.CreateBuilder(args);
builder.Services...
builder.Host.UseWindowsService();
builder.Host.UseSerilog((ctx, lc) => lc
.WriteTo.Console()
.WriteTo.File(_logDir)
.ReadFrom.Configuration(ctx.Configuration));
WebApplication app = builder.Build();
app.Run();
It works with IHostBuilder:
public static IHostBuilder CreateServiceHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
..
What am I doing wrong?

As the error says, you need to set your ContentRootPath with WebApplicationOptions
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
ContentRootPath = #"C:\foo\foo\publish",
Args = args
});

Related

How to handle deprecation of IWebHostBuilder.UseSerilog() when IWebHostBuilder is still needed?

The UseSerilog() extension is deprecated* for IWebHostBuilder in serilog-aspnetcore version 5.0.0. However I'm still using a IWebHostBuilder and a Startup class (aspnetcore 6), and IWebHostBuilder is not deprecated.
Since deprecation implies future removal, how should I leverage Serilog going forward?
reference:
https://github.com/serilog/serilog-aspnetcore/releases/tag/v5.0.0
"mark IWebHostBuilder extensions as obsolete on platforms with IHostBuilder"
I was able to get this to work by switching to IHostBuilder instead of IWebHostBuilder. The key in my case was to call ConfigureWebHostDefaults (or ConfigureWebHost), where you can then utilize an IWebHostBuilder.
In this way, I could call UseSerilog on the IHostBuilder while still utilizing the Startup class as before with an IWebHostBuilder.
Example:
public static void Main(string[] args)
{
// temp initial logging
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
using var app =
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webHostBuilder
=> webHostBuilder.ConfigureAppConfiguration((hostingContext, config) =>
_ = config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", false, true))
.UseStartup<Startup>())
.UseSerilog(
(hostingContext, loggerConfig) =>
loggerConfig
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext(),
writeToProviders: true)
.Build();
app.Run();
}
I Solved with:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();

NService Bus throwing AnException While Using Castle Windsor

static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseNServiceBus(ctx =>
{
var endpointConfiguration = new EndpointConfiguration("bindingName");
var containerSettings = endpointConfiguration.UseContainer(new WindsorServiceProviderFactory());
containerSettings.ConfigureContainer(c => ConfigureCastleWindsor(c));
endpointConfiguration.SendFailedMessagesTo("error");
endpointConfiguration.AuditProcessedMessagesTo("audit");
endpointConfiguration.EnableInstallers();
return endpointConfiguration;
});
}
private static IWindsorContainer ConfigureCastleWindsor(IWindsorContainer c)
{
return c.Register(Component.For<DbStore>()
.DependsOn(Dependency.OnValue("Connection", ConfigurationManager.ConnectionStrings["name"].ConnectionString))
.LifeStyle.PerThread,
Component.For<IManageUnitsOfWork>().ImplementedBy<LinqUnitOfWork>().LifestyleTransient(),
Component.For<IMapper>().UsingFactoryMethod(x => new Mapper(ContractAutoMapper.Start())).LifestyleSingleton());
}
I am referencing Nservice Bus document link (https://docs.particular.net/nservicebus/dependency-injection/castlewindsor) to implement third part castle Windsor as DI in Nservice Bus 7.2.3 + NServiceBus.Extensions.Hosting .
Packages Information :
Host Window Service packages - NServiceBus.Extensions.Hosting.1.0.1
NServiceBus.Extensions.DependencyInjection (1.0.1)
Castle.Core (4.2.0)
Castle.Windsor (4.1.1)
Castle.Windsor.MsDependencyInjection (3.0.0)
NServiceBus.CastleWindsor (7.0.0)
NOTE: Third-party Castle Windsor with the internally managed mode
Error Information: An internally managed container has already been configured using 'EndpointConfiguration.UseContainer'. It is not possible to use both an internally managed container and an externally managed container.
Stack Trace: NServiceBus.ContainerComponent.InitializeWithExternallyManagedContainer(IConfigureComponents configureComponents)
at NServiceBus.EndpointCreator.CreateWithExternallyManagedContainer(EndpointConfiguration endpointConfiguration, IConfigureComponents configureComponents)
at NServiceBus.HostBuilderExtensions.<>c__DisplayClass0_0.<UseNServiceBus>b__0(HostBuilderContext ctx, IServiceCollection serviceCollection)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Report.Program.Main(String[] args)
I am not using any external manager mode but still, I am running with this error, could you please let us know how do we use third-party Castle Windsor as DI.
The error message states what the issue is. When using a custom container using NServiceBus.Extensions.Hosting package, you'll need to do so before and outside of the UseNServiceBus extension method. Here's a working snippet:
static IHostBuilder CreateHost()
{
return Host.CreateDefaultBuilder()
.UseServiceProviderFactory(context => new WindsorServiceProviderFactory())
.ConfigureContainer<WindsorContainer>((ctx, container) =>
{
container.Register(Component.For<MyService>()); // <- Windsor registrations can go here.
})
.UseNServiceBus(nsb =>
{
//Don't apply the custom container here.
var endpointConfiguration = new EndpointConfiguration("Samples.Castle");
endpointConfiguration.UseTransport<LearningTransport>();
return endpointConfiguration;
});
}

Autofac not working after update

I have updated Autofac.Mvc from version 3.2.1 to 3.3.0, i also updated all other packages including EF, MVC, WebActivatorEx etc and after update it is giving error on my controller
no parameterless constructor defined for this object
I put a breakpoint in my initialization class and i found that it is not even hitting the breakpoint. I've a separate dependency resolution layer in my project and this is the code for initialization class
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]
namespace MyApp.Bootstrapper
{
public class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
const string nameOrConnectionString = "name=AppContext";
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterGeneric(typeof(EntityRepository<>)).As(typeof(IRepository<>)).InstancePerHttpRequest();
builder.RegisterGeneric(typeof(Service<>)).As(typeof(IService<>)).InstancePerHttpRequest();
builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerHttpRequest();
builder.Register<IEntitiesContext>(b =>
{
var logger = b.Resolve<ILogger>();
var context = new AspnetIdentityWithOnionContext(nameOrConnectionString, logger);
return context;
}).InstancePerHttpRequest();
builder.Register(b => NLogLogger.Instance).SingleInstance();
builder.RegisterModule(new IdentityModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
Please guide me with this.
The bootstrapper project bin dlls must be loaded with a web project dll ,so in the bootstrapper project >> select properties >> select build tab >> change output path to >> web project bin (ex:..\myApp.web\bin)

Autofac TypeLoadException when upgrading MVC 4 -> 5

Trying to upgrade a project from MVC3to MVC5,
the 3->4 part went well and I could run the project.
However, after updating probably everything for mvc5,
I'm getting an exception
Inheritance security rules violated by type: 'Autofac.Integration.Web.Mvc.AutofacControllerFactory'. Derived types must either match the security accessibility of the base type or be less accessible.
on this row of Application_Start()
InitContainerProvider();
the method being called:
protected void InitContainerProvider()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<PeriodsProxy>().As<IPeriods>().AsWcfProxy();
_containerProvider = new ContainerProvider(builder.Build());
var factory = new AutofacControllerFactory(_containerProvider);
ControllerBuilder.Current.SetControllerFactory(factory);
}
Try the following
protected void InitContainerProvider()
{
var builder = new ContainerBuilder();
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterType<PeriodsProxy>().As<IPeriods>().AsWcfProxy();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
_containerProvider = new ContainerProvider(builder.Build());
DependencyResolver.SetResolver(new AutofacDependencyResolver(_containerProvider.ApplicationContainer.BeginLifetimeScope()));
}
This example uses the package NuGet: Autofac.Mvc5

Autofac Azure Mobile Service integration issue

I gets '..make sure that the controller has a parameterless public constructor autofac..'
My controller:
public class AccountController : ApiController
{
private IAccountService _accountService;
public AccountController(IAccountService accountService)
{
_accountService = accountService;
}
...
}
My autofac configuration:
protected void Application_Start()
{
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<AccountService>().As<IAccountService>().InstancePerRequest();
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
Whats wrong with my code?
Full error message:
Exception=System.InvalidOperationException: An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor. ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyProj.Api.Controllers.AccountController' can be invoked with the available services and parameters:
Cannot resolve parameter 'MyProj.Engine.Services.Interfaces.IAccountService accountService' of constructor 'Void .ctor(MyProj.Engine.Services.Interfaces.IAccountService)'.
Fixed myself. Actually the issue was that project is Azure Mobile Service.
It was my first experience with it and I have configured it as I used to do for WebApi. But as I understood after last googling this project type base on OWIN.
That's good article about: http://blogs.msdn.com/b/azuremobile/archive/2014/04/19/autofac-and-azure-mobile-services-net-backend.aspx
So it should be like this:
ConfigOptions options = new ConfigOptions();
ConfigBuilder builder = new ConfigBuilder(options, (httpConfig, autofac) =>
{
autofac.RegisterInstance(new MyService()).As<IMyService>();
});
HttpConfiguration config = ServiceConfig.Initialize(builder);

Resources