Scope was not available. Did you forget to call container.BeginScope()? - c#

Hello I want to using castle windosr in .net core and I have get bellow error in .net core:
Scope was not available. Did you forget to call
container.BeginScope()?
my code is :
public IServiceProvider 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;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var container = new WindsorContainer();
//container.BeginScope();
Bootstrapper.WireUp(container);
FrameworkBootstrapper.WireUp(container);
var configureServices = WindsorRegistrationHelper.CreateServiceProvider(container, services);
return configureServices;
}
I added the error image .
in your option if i add container.BeginScope(); after var container = new WindsorContainer(); Is it the right way? Is there any problem?
WindsorRegistrationHelper is a package between .net core built in ioc and castle
you can see on below link:
https://github.com/volosoft/castle-windsor-ms-adapter

Related

Change default cookie names in ASP.NET Core MVC

I would like to change the default Cookie name for .AspNetCore.Antiforgery.xxx in ASP.NET Core 3.X MVC, however I do not seem to find any documentation on it. Is it even possible?
The only one I found to be able to alter was this:
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
options.ConsentCookie.Name = "GDRP";
});
This is achievable using AddAntiforgery. Here's an example taken from the docs and modified accordingly:
services.AddAntiforgery(options =>
{
options.Cookie.Name = "YourCookieName";
});
There's a useful page in the docs that lists the built-in ASP.NET Core cookies and where the configuration for each comes from.
For .NET 5.0 and higher
in ProjectRoot/Startup.cs class
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "your_cookie_name";
});
// ...
services.AddControllers();
}
ok, found it already, for those that are looking
services.AddAntiforgery(options =>
{
options.Cookie.Name = "my-x-name";
options.HeaderName = "my-x-name";
});
It will accept any string, need to validate if it works or if something else needs to be updated...

GetService with IOptionsMonitor<Settings> returns null object

I have the following on an ASP.NET Core 3.0 application:
IServiceCollection services = new ServiceCollection();
services.AddSingleton<Settings>(new Settings { DefaultPageSize = 40 });
IServiceProvider provider = services.BuildServiceProvider();
var result = provider.GetService<IOptionsMonitor<Settings>>();
On the last line result is null ... Any idea why?
services.AddSingleton<Settings>(...
Does not automatically associate Settings with the IOptionsMonitor feature.
Need to configure that Settings class as an option with the service collection using one of the Options pattern extensions
For example
IServiceCollection services = new ServiceCollection();
// Options bound and configured by a delegate
services.Configure<Settings>(option => {
option.DefaultPageSize = 40;
});
IServiceProvider provider = services.BuildServiceProvider();
var result = provider.GetService<IOptionsMonitor<Settings>>();
Reference Options pattern in ASP.NET Core: Configure simple options with a delegate

.net core generic host builder use connection string from one context in a subsequent context DI registration

I need to register two DbContext classes in my .net core 2.1 application using the built in Ioc container. The connection details for the second context is stored in the database from the first context, so the registrations would look something like
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>( /* Connection string from context1 here */ )
.AddHostedService<MyHostedService>();
});
Is there any way for me to register Context1, get the values and then use that to register Context2?
Use one of the overloads that will give you access to the service provider
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>((serviceProvider, options) => {
var context1 = serviceProvider.GetService<Context1>();
var connectionString = /* get Connection string from context1 here */
options.UseSqlServer(connectionString);
})
.AddHostedService<MyHostedService>();
});
Reference AddDbContext<TContext>(IServiceCollection, Action<IServiceProvider,DbContextOptionsBuilder>, ServiceLifetime, ServiceLifetime)

No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[SolutionName.Areas.Identity.Data.SolutionNameUser]' has been registered

When i added the EmailSender for password recovery and email confirmation using microsofts guide I got this message on startup. I've tripple checked if i've done everything in the guide correctly and I have (from what i can see) and the app worked as it should before i added everything from the guide. I've done this before on another app and didnt have any problems with it, so i feel that i'm stuck now.
I'm using Razor Pages.
My ConfigureServices in Startup.cs:
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;
});
services.AddAuthentication()
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
})
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
}

Autofac Web API 2 and Owin resolve in StartupConfig

I have a project that is both OWIN and Web API 2.
I have tried to follow the instructions as best as I can.
Inside my Configration method in the StartupConfig class I have this:
// Get our configuration
var config = new HttpConfiguration();
var container = ConfigureInversionOfControl(app, config);
var scope = config.DependencyResolver.GetRequestLifetimeScope();
var serverOptions = ConfigureOAuthTokenGeneration(app, scope);
//** removed for brevity **//
// Cors must be first, or it will not work
app.UseCors(CorsOptions.AllowAll);
// Register the Autofac middleware FIRST. This also adds
// Autofac-injected middleware registered with the container.
app.UseAutofacMiddleware(container);
//app.UseAutofacWebApi(config);
app.UseOAuthAuthorizationServer(serverOptions);
app.UseWebApi(config);
My ConfigurInversionOfControl method looks like this:
private static IContainer ConfigureInversionOfControl(IAppBuilder app, HttpConfiguration config)
{
// Create our container
var builder = new ContainerBuilder();
// You can register controllers all at once using assembly scanning...
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// Add our dependencies (Can't use life because this is available to all controllers http://stackoverflow.com/questions/36173210/get-same-instance-of-a-component-registered-with-autofac-as-instanceperlifetimes)
builder.RegisterType<UnitOfWork<DatabaseContext>>().As<IUnitOfWork>().InstancePerRequest();
// Register our services
builder.Register(c => new AdvancedEncryptionStandardProvider(ConfigurationManager.AppSettings["rm:key"], ConfigurationManager.AppSettings["rm:secret"])).As<IAdvancedEncryptionStandardProvider>();
builder.RegisterType<LogService>().As<ILogService>();
builder.RegisterType<EmailService>().As<IEmailService>();
builder.RegisterType<RefreshTokenService>().As<IRefreshTokenService>();
// Register our providers
builder.Register(c => new SendGridProvider(c.Resolve<IUnitOfWork>(), c.Resolve<IEmailService>(), ConfigurationManager.AppSettings["SendGridApiKey"])).As<ISendGridProvider>();
builder.RegisterType<LogProvider>().As<ILogProvider>();
builder.RegisterType<RefreshTokenProvider>().As<IAuthenticationTokenProvider>();
builder.RegisterType<OAuthProvider>().As<OAuthProvider>();
// Build
var container = builder.Build();
// Lets Web API know it should locate services using the AutofacWebApiDependencyResolver
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
// Return our container
return container;
}
Now I have set this up (I assume correctly). How do I resolve one of the services in my StartupConfig class?
I need to be able to create an instance of the OAuthProvider and RefreshTokenProvider. I tried something similar to this:
// Get our providers
var authProvider = scope.Resolve<OAuthProvider>();
var refreshTokenProvider = scope.Resolve<IAuthenticationTokenProvider>();
// Create our OAuth options
return new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true, // TODO: Remove this line
TokenEndpointPath = new PathString("/oauth/access_token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AccessTokenFormat = new Business.Authentication.JwtFormat("http://localhost:62668"),
Provider = authProvider,
RefreshTokenProvider = refreshTokenProvider
};
But when it reaches the line var authProvider = scope.Resolve<OAuthProvider>();, I get an error stating:
Parameter cannot be null: Parameter name: context
Now I would assume that the context has not been created yet, so I assume I am doing something wrong with my resolve.
Can anyone help?
This was actually really simple.
I needed the change the scope from:
var scope = config.DependencyResolver.GetRequestLifetimeScope();
to
var scope = config.DependencyResolver.GetRootLifetimeScope();
I assume because the "request" is not available in the StartupConfig class.
Anyway, changing this fixed my issue.

Categories

Resources