none
add-migration is not taking DI values from startup.cs, but it works for http request(I mean for postman test cases). It works when I do it from OnConfiguring method but not from DI. RRS feed

  • Question

  • > ConfigureServices in startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            try { 
            services.AddApplicationInsightsTelemetry(Configuration);
            

            services.AddSingleton<IConfiguration>(Configuration);
            services.AddSingleton<WebApiExceptionHandler>();
            JsonSerializerSettings globalSettings = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore,
                // for UTC for datetime
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };
            var isoDateTimeConverter = new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"
            };
            globalSettings.Converters.Add(isoDateTimeConverter);
            services.AddSingleton(globalSettings);
            var schemaRepository = Configuration.GetValue<string>("SchemaRepository");
            services.Configure<PatientApiOptions>(Configuration.GetSection("PatientServiceOptions"));
            services.Configure<DocumentApiOptions>(Configuration.GetSection("DocumentServiceOptions"));
            services.AddPatientApi(schemaRepository);
            services.AddDocumentApi(schemaRepository,globalSettings);
                services.AddScoped<ISalesForceApi, SalesForceApi>();
            var patientConnectionString = Configuration.GetConnectionString("PatientConnection");
            var documentConnectionString = Configuration.GetConnectionString("DocumentConnection");
            services.AddPatientRepository(patientConnectionString);
            services.AddDocumentRepository(documentConnectionString);
            services.AddSalesforceRepository(patientConnectionString); // As patient and sf can use same conn.
                JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
                var ssoService = Configuration.GetSection("Endpoints")?["SingleSignOnService"];
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                    .AddIdentityServerAuthentication(x=> {
                    x.Authority = ssoService;
                    x.RequireHttpsMetadata = !_environment.IsDevelopment();
                    x.ApiName = "backend.patientdata.api";
                    x.EnableCaching = true;
                    x.CacheDuration = TimeSpan.FromMinutes(10);
                });
                
                // Add framework services.
                var builder = services.AddMvc();
            if (!_environment.IsDevelopment())
            {
                builder.AddMvcOptions(options => options.Filters.Add(new RequireHttpsAttribute()));
            }
            builder.AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = globalSettings.ContractResolver;
                options.SerializerSettings.NullValueHandling = globalSettings.NullValueHandling;
                options.SerializerSettings.DateTimeZoneHandling = globalSettings.DateTimeZoneHandling;
                options.SerializerSettings.Converters.Add(isoDateTimeConverter);
            });
            //services.AddCors(); // to run TestApp
            services.AddRouting(options => options.LowercaseUrls = true);
            if (!_environment.IsProduction())
            {
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1",
                        new Info
                        {
                            Title = "Patient Data Services",
                            Description = "For Schema definitions see <a href=\"./../schema/all\">here</a>"
                        });
                    c.DescribeAllEnumsAsStrings();
                    c.DocumentFilter<LowercaseDocumentFilter>();
                });
            }
            services.AddSingleton<IAppInsightsLogger>(new AppInsightsLogger(TelemetryClient));
            services.AddSingleton<IAuditLogAdapter>(
                new AuditLogAdapter(Configuration.GetConnectionString("AuditLogConnection")));
            }
            catch (Exception exception)
            {
                TelemetryClient.TrackEvent("PatientData Service Bootstrapping FAILED in ConfigureServices()");
                TelemetryClient.TrackException(exception);
                throw;
            }
        }

    > AddPatientRepository:

        public static IServiceCollection AddPatientRepository(
            this IServiceCollection services
            , string connectionString)
        {
            services.AddEntityFrameworkSqlServer();
            Action<DbContextOptionsBuilder> dbContextOptionsAction = builder =>
                builder.UseSqlServer(connectionString);
            services.AddDbContext<PatientDataContext>(dbContextOptionsAction);
            services.AddScoped<IPatientRepository, PatientRepository>();
            return services;
        }
    Monday, July 22, 2019 9:06 PM

All replies

  • Why are you using the generic repository over EF that is already using the repository pattern?

    https://www.thereformedprogrammer.net/is-the-repository-pattern-useful-with-entity-framework-core/

    The repository pattern is a domain pattern and not a persistence pattern.

    https://martinfowler.com/eaaCatalog/repository.html

    https://programmingwithmosh.com/net/common-mistakes-with-the-repository-pattern/

    https://www.infoworld.com/article/3117713/design-patterns-that-i-often-avoid-repository-pattern.html

    https://blog.sapiensworks.com/post/2012/04/07/Just-Stop-It!-The-Domain-Model-Is-Not-The-Persistence-Model.aspx

    Now, you don't need Postmon to debug a WebAPI. You can push the VS Core WebAPI project to local IIS and test, debug and develop against local IIS.

    https://blog.sapiensworks.com/post/2012/04/07/Just-Stop-It!-The-Domain-Model-Is-Not-The-Persistence-Model.aspx

    You set the WebAPI as the startup project in VS. You start the project in VS using the debugger 'Start with Debugger'. The browser will have a blank page after the project has started successfully. You go back to VS and to the Debugger menu,  select 'Attach to Process', find the wpw3.exe that is servicing the App Pool that is hosting the WebAPI and you attach to the wpw3.exe.

    You go back to VS and set a breakpoint in the code.  You then go back to the browser and enter a URL address that points to a WebAPI action method that will eventually lead to the code that has a breakpoint set. Any results the controller action method returns as Json, XML etc. and ect. will be shown in the browser. 

    https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-enable-debugging-for-aspnet-applications?view=vs-2017

    Tuesday, July 23, 2019 2:06 AM
  • My issue is related to add-migration command. when I use add-migration its not going through startup.cs where I am defining my dependencies.
    Tuesday, July 23, 2019 4:22 AM
  • My issue is related to add-migration command. when I use add-migration its not going through startup.cs where I am defining my dependencies.

    Myself, I don't use the EF migration stuff. I am more into using MS SQL Server administration tools like SSMS.

    However, you can post to the ASP.NET Core forum and also to the EF forum in ASP.NET forums and seek help there.

    http://forums.asp.net/

    Tuesday, July 23, 2019 8:36 AM