Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Startup Class
- public class Startup
- {
- //Startup Method
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
- // Service Provider for ConfigureService
- public IServiceProvider ConfigureServices(IServiceCollection services)
- {
- //Registery
- RegisterAppInsights(services);
- // Add framework services.
- services.AddMvc(options =>
- {
- options.Filters.Add(typeof(HttpGlobalExceptionFilter));
- }).AddControllersAsServices(); //Injecting Controllers themselves thru DI
- // Configure GracePeriodManager Hosted Service
- services.AddSingleton<IHostedService, GracePeriodManagerService>();
- services.AddTransient<IOrderingIntegrationEventService, OrderingIntegrationEventService>();
- //Code For Health Checks
- services.AddHealthChecks(checks =>
- {
- var minutes = 1;
- if (int.TryParse(Configuration["HealthCheck:Timeout"], out var minutesParsed))
- {
- minutes = minutesParsed;
- }
- checks.AddSqlCheck("OrderingDb", Configuration["ConnectionString"], TimeSpan.FromMinutes(minutes));
- });
- //Code is for Adding Entity Framework with Sql Server
- services.AddEntityFrameworkSqlServer()
- .AddDbContext<OrderingContext>(options =>
- {
- options.UseSqlServer(Configuration["ConnectionString"],
- sqlServerOptionsAction: sqlOptions =>
- {
- sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
- sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
- });
- },
- ServiceLifetime.Scoped //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
- );
- //Code For Add the DBContext of database
- services.AddDbContext<IntegrationEventLogContext>(options =>
- {
- options.UseSqlServer(Configuration["ConnectionString"],
- sqlServerOptionsAction: sqlOptions =>
- {
- //Migration Code on startup
- services.AddSwaggerGen(options =>
- {
- options.DescribeAllEnumsAsStrings();
- options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
- {
- Title = "Ordering HTTP API",
- Version = "v1",
- Description = "The Ordering Service HTTP API",
- TermsOfService = "Terms Of Service"
- });
- options.AddSecurityDefinition("oauth2", new OAuth2Scheme
- {
- Type = "oauth2",
- Flow = "implicit",
- AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
- TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
- Scopes = new Dictionary<string, string>()
- {
- { "orders", "Ordering API" }
- }
- });
- options.OperationFilter<AuthorizeCheckOperationFilter>();
- });
- services.AddCors(options =>
- {
- options.AddPolicy("CorsPolicy",
- builder => builder.AllowAnyOrigin()
- .AllowAnyMethod()
- .AllowAnyHeader()
- .AllowCredentials());
- });
- // Add application services.
- services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
- services.AddTransient<IIdentityService, IdentityService>();
- services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>(
- sp => (DbConnection c) => new IntegrationEventLogService(c));
- services.AddTransient<IOrderingIntegrationEventService, OrderingIntegrationEventService>();
- if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
- {
- services.AddSingleton<IServiceBusPersisterConnection>(sp =>
- {
- var logger = sp.GetRequiredService<ILogger<DefaultServiceBusPersisterConnection>>();
- var serviceBusConnectionString = Configuration["EventBusConnection"];
- var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);
- return new DefaultServiceBusPersisterConnection(serviceBusConnection, logger);
- });
- }
- else
- {
- services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
- {
- var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
- var factory = new ConnectionFactory()
- {
- HostName = Configuration["EventBusConnection"]
- };
- if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
- {
- factory.UserName = Configuration["EventBusUserName"];
- }
- if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
- {
- factory.Password = Configuration["EventBusPassword"];
- }
- var retryCount = 5;
- if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
- {
- retryCount = int.Parse(Configuration["EventBusRetryCount"]);
- }
- return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
- });
- }
- RegisterEventBus(services);
- ConfigureAuthService(services);
- services.AddOptions();
- //configure autofac
- var container = new ContainerBuilder();
- container.Populate(services);
- container.RegisterModule(new MediatorModule());
- container.RegisterModule(new ApplicationModule(Configuration["ConnectionString"]));
- return new AutofacServiceProvider(container.Build());
- }
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- loggerFactory.AddConsole(Configuration.GetSection("Logging"));
- loggerFactory.AddDebug();
- loggerFactory.AddAzureWebAppDiagnostics();
- loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);
- var pathBase = Configuration["PATH_BASE"];
- if (!string.IsNullOrEmpty(pathBase))
- {
- loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
- app.UsePathBase(pathBase);
- }
- app.UseCors("CorsPolicy");
- ConfigureAuth(app);
- app.UseMvcWithDefaultRoute();
- app.UseSwagger()
- .UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Ordering.API V1");
- c.ConfigureOAuth2("orderingswaggerui", "", "", "Ordering Swagger UI");
- });
- ConfigureEventBus(app);
- }
- private void RegisterAppInsights(IServiceCollection services)
- {
- services.AddApplicationInsightsTelemetry(Configuration);
- var orchestratorType = Configuration.GetValue<string>("OrchestratorType");
- if (orchestratorType?.ToUpper() == "K8S")
- {
- // Enable K8s telemetry initializer
- services.EnableKubernetes();
- }
- if (orchestratorType?.ToUpper() == "SF")
- {
- // Enable SF telemetry initializer
- services.AddSingleton<ITelemetryInitializer>((serviceProvider) =>
- new FabricTelemetryInitializer());
- }
- }
- // The Below Code is for Event Bus Configuration you can check it and tell me if anything is wrong........
- private void ConfigureEventBus(IApplicationBuilder app)
- {
- var eventBus = app.ApplicationServices.GetRequiredService<BuildingBlocks.EventBus.Abstractions.IEventBus>();
- private void ConfigureAuthService(IServiceCollection services)
- {
- // prevent from mapping "sub" claim to nameidentifier.
- JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
- var identityUrl = Configuration.GetValue<string>("IdentityUrl");
- services.AddAuthentication(options =>
- {
- options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- }).AddJwtBearer(options =>
- {
- options.Authority = identityUrl;
- options.RequireHttpsMetadata = false;
- options.Audience = "orders";
- });
- }
- protected virtual void ConfigureAuth(IApplicationBuilder app)
- {
- if (Configuration.GetValue<bool>("UseLoadTest"))
- {
- app.UseMiddleware<ByPassAuthMiddleware>();
- }
- app.UseAuthentication();
- }
- private void RegisterEventBus(IServiceCollection services)
- {
- var subscriptionClientName = Configuration["SubscriptionClientName"];
- if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
- {
- services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
- {
- var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>();
- var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
- var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>();
- var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
- return new EventBusServiceBus(serviceBusPersisterConnection, logger,
- eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope);
- });
- }
- else
- {
- services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
- {
- var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
- var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
- var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
- var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
- var retryCount = 5;
- if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
- {
- retryCount = int.Parse(Configuration["EventBusRetryCount"]);
- }
- return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
- });
- }
- services.AddSingleton<IEventBusSubscriptionsManager,
- InMemoryEventBusSubscriptionsManager>();
- }
- }
- }
- This is the error message, Help me with this autofac dependency error:
- 'An error occurred during the activation of a particular registration. See
- the inner exception for details. Registration: Activator =
- IEventBus(DelegateActivator), Services =
- [InfiniteWorx.MRU.BuildingBlocks.EventBus.Abstractions.IEventBus],
- Lifetime=Autofac.Core.Lifetime.RootScopeLifetime, Sharing = Shared,
- Ownership =OwnedByLifetimeScope'
Add Comment
Please, Sign In to add comment