Guest User

Untitled

a guest
Apr 30th, 2018
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.39 KB | None | 0 0
  1. // Startup Class
  2. public class Startup
  3. {
  4. //Startup Method
  5. public Startup(IConfiguration configuration)
  6. {
  7. Configuration = configuration;
  8. }
  9.  
  10. public IConfiguration Configuration { get; }
  11. // Service Provider for ConfigureService
  12. public IServiceProvider ConfigureServices(IServiceCollection services)
  13. {
  14. //Registery
  15. RegisterAppInsights(services);
  16.  
  17. // Add framework services.
  18. services.AddMvc(options =>
  19. {
  20. options.Filters.Add(typeof(HttpGlobalExceptionFilter));
  21. }).AddControllersAsServices(); //Injecting Controllers themselves thru DI
  22.  
  23. // Configure GracePeriodManager Hosted Service
  24. services.AddSingleton<IHostedService, GracePeriodManagerService>();
  25.  
  26. services.AddTransient<IOrderingIntegrationEventService, OrderingIntegrationEventService>();
  27. //Code For Health Checks
  28. services.AddHealthChecks(checks =>
  29. {
  30. var minutes = 1;
  31. if (int.TryParse(Configuration["HealthCheck:Timeout"], out var minutesParsed))
  32. {
  33. minutes = minutesParsed;
  34. }
  35. checks.AddSqlCheck("OrderingDb", Configuration["ConnectionString"], TimeSpan.FromMinutes(minutes));
  36. });
  37. //Code is for Adding Entity Framework with Sql Server
  38. services.AddEntityFrameworkSqlServer()
  39. .AddDbContext<OrderingContext>(options =>
  40. {
  41. options.UseSqlServer(Configuration["ConnectionString"],
  42. sqlServerOptionsAction: sqlOptions =>
  43. {
  44. sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
  45. sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
  46. });
  47. },
  48. ServiceLifetime.Scoped //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
  49. );
  50. //Code For Add the DBContext of database
  51. services.AddDbContext<IntegrationEventLogContext>(options =>
  52. {
  53. options.UseSqlServer(Configuration["ConnectionString"],
  54. sqlServerOptionsAction: sqlOptions =>
  55. {
  56. //Migration Code on startup
  57.  
  58. services.AddSwaggerGen(options =>
  59. {
  60. options.DescribeAllEnumsAsStrings();
  61. options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
  62. {
  63. Title = "Ordering HTTP API",
  64. Version = "v1",
  65. Description = "The Ordering Service HTTP API",
  66. TermsOfService = "Terms Of Service"
  67. });
  68.  
  69. options.AddSecurityDefinition("oauth2", new OAuth2Scheme
  70. {
  71. Type = "oauth2",
  72. Flow = "implicit",
  73. AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
  74. TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
  75. Scopes = new Dictionary<string, string>()
  76. {
  77. { "orders", "Ordering API" }
  78. }
  79. });
  80.  
  81. options.OperationFilter<AuthorizeCheckOperationFilter>();
  82. });
  83.  
  84. services.AddCors(options =>
  85. {
  86. options.AddPolicy("CorsPolicy",
  87. builder => builder.AllowAnyOrigin()
  88. .AllowAnyMethod()
  89. .AllowAnyHeader()
  90. .AllowCredentials());
  91. });
  92.  
  93. // Add application services.
  94. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  95. services.AddTransient<IIdentityService, IdentityService>();
  96. services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>(
  97. sp => (DbConnection c) => new IntegrationEventLogService(c));
  98.  
  99. services.AddTransient<IOrderingIntegrationEventService, OrderingIntegrationEventService>();
  100.  
  101. if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
  102. {
  103. services.AddSingleton<IServiceBusPersisterConnection>(sp =>
  104. {
  105. var logger = sp.GetRequiredService<ILogger<DefaultServiceBusPersisterConnection>>();
  106.  
  107. var serviceBusConnectionString = Configuration["EventBusConnection"];
  108. var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);
  109.  
  110. return new DefaultServiceBusPersisterConnection(serviceBusConnection, logger);
  111. });
  112. }
  113. else
  114. {
  115. services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
  116. {
  117. var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
  118.  
  119.  
  120. var factory = new ConnectionFactory()
  121. {
  122. HostName = Configuration["EventBusConnection"]
  123. };
  124.  
  125. if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
  126. {
  127. factory.UserName = Configuration["EventBusUserName"];
  128. }
  129.  
  130. if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
  131. {
  132. factory.Password = Configuration["EventBusPassword"];
  133. }
  134.  
  135. var retryCount = 5;
  136. if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
  137. {
  138. retryCount = int.Parse(Configuration["EventBusRetryCount"]);
  139. }
  140.  
  141. return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
  142. });
  143. }
  144.  
  145. RegisterEventBus(services);
  146. ConfigureAuthService(services);
  147. services.AddOptions();
  148.  
  149. //configure autofac
  150.  
  151. var container = new ContainerBuilder();
  152. container.Populate(services);
  153.  
  154. container.RegisterModule(new MediatorModule());
  155. container.RegisterModule(new ApplicationModule(Configuration["ConnectionString"]));
  156.  
  157. return new AutofacServiceProvider(container.Build());
  158. }
  159.  
  160.  
  161. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  162. {
  163. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  164. loggerFactory.AddDebug();
  165. loggerFactory.AddAzureWebAppDiagnostics();
  166. loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);
  167.  
  168. var pathBase = Configuration["PATH_BASE"];
  169. if (!string.IsNullOrEmpty(pathBase))
  170. {
  171. loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
  172. app.UsePathBase(pathBase);
  173. }
  174.  
  175. app.UseCors("CorsPolicy");
  176.  
  177. ConfigureAuth(app);
  178. app.UseMvcWithDefaultRoute();
  179.  
  180. app.UseSwagger()
  181. .UseSwaggerUI(c =>
  182. {
  183. c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Ordering.API V1");
  184. c.ConfigureOAuth2("orderingswaggerui", "", "", "Ordering Swagger UI");
  185. });
  186.  
  187. ConfigureEventBus(app);
  188. }
  189.  
  190. private void RegisterAppInsights(IServiceCollection services)
  191. {
  192. services.AddApplicationInsightsTelemetry(Configuration);
  193. var orchestratorType = Configuration.GetValue<string>("OrchestratorType");
  194.  
  195. if (orchestratorType?.ToUpper() == "K8S")
  196. {
  197. // Enable K8s telemetry initializer
  198. services.EnableKubernetes();
  199. }
  200. if (orchestratorType?.ToUpper() == "SF")
  201. {
  202. // Enable SF telemetry initializer
  203. services.AddSingleton<ITelemetryInitializer>((serviceProvider) =>
  204. new FabricTelemetryInitializer());
  205. }
  206. }
  207. // The Below Code is for Event Bus Configuration you can check it and tell me if anything is wrong........
  208.  
  209. private void ConfigureEventBus(IApplicationBuilder app)
  210. {
  211. var eventBus = app.ApplicationServices.GetRequiredService<BuildingBlocks.EventBus.Abstractions.IEventBus>();
  212.  
  213. private void ConfigureAuthService(IServiceCollection services)
  214. {
  215. // prevent from mapping "sub" claim to nameidentifier.
  216. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
  217.  
  218. var identityUrl = Configuration.GetValue<string>("IdentityUrl");
  219.  
  220. services.AddAuthentication(options =>
  221. {
  222. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  223. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  224.  
  225. }).AddJwtBearer(options =>
  226. {
  227. options.Authority = identityUrl;
  228. options.RequireHttpsMetadata = false;
  229. options.Audience = "orders";
  230. });
  231. }
  232.  
  233. protected virtual void ConfigureAuth(IApplicationBuilder app)
  234. {
  235. if (Configuration.GetValue<bool>("UseLoadTest"))
  236. {
  237. app.UseMiddleware<ByPassAuthMiddleware>();
  238. }
  239.  
  240. app.UseAuthentication();
  241. }
  242.  
  243. private void RegisterEventBus(IServiceCollection services)
  244. {
  245. var subscriptionClientName = Configuration["SubscriptionClientName"];
  246.  
  247. if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
  248. {
  249. services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
  250. {
  251. var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>();
  252. var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
  253. var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>();
  254. var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
  255.  
  256. return new EventBusServiceBus(serviceBusPersisterConnection, logger,
  257. eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope);
  258. });
  259. }
  260. else
  261. {
  262. services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
  263. {
  264. var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
  265. var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
  266. var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
  267. var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
  268.  
  269. var retryCount = 5;
  270. if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
  271. {
  272. retryCount = int.Parse(Configuration["EventBusRetryCount"]);
  273. }
  274.  
  275. return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
  276. });
  277. }
  278.  
  279. services.AddSingleton<IEventBusSubscriptionsManager,
  280. InMemoryEventBusSubscriptionsManager>();
  281. }
  282. }
  283. }
  284.  
  285. This is the error message, Help me with this autofac dependency error:
  286.  
  287.  
  288. 'An error occurred during the activation of a particular registration. See
  289. the inner exception for details. Registration: Activator =
  290. IEventBus(DelegateActivator), Services =
  291. [InfiniteWorx.MRU.BuildingBlocks.EventBus.Abstractions.IEventBus],
  292. Lifetime=Autofac.Core.Lifetime.RootScopeLifetime, Sharing = Shared,
  293. Ownership =OwnedByLifetimeScope'
Add Comment
Please, Sign In to add comment