Notes from building a first ASP.Net Core App (part 3)

  1. Now that I’ve shown how to obtain a configuration method, let’s make this code a little bit better. Let’s make it interact with a configuration class and strongly type the return of the configuration item.
  2. To do this, add a New Folder at the same level of the project as the wwwroot folder, and call it Services. Add a file to that called MyCustomConfiguration.cs. Here’s what my folder structure looks like:
    my-first-asp-net-core-app-folder-structure-1
  3. Inside the MyCustomConfiguration.cs file, we want to add a method that returns the contents of the configuration. The Configuration Service will need to be injected into the Startup.cs file via Dependency Injection. So to keep this simple, I’ll break it into two parts. The first part is to return the string from a method, and then later I’ll get it to register a service to load the configuration.
  4. For this to work, we add an Interface (which sets it up to be injectable) and then return the string from the concrete class.
    namespace MyFirstAspDotNetCoreApp.Services
    {
        public interface IMyCustomConfiguration
        {
            string GetMyCustomMessage();
        }
    
        public class MyCustomConfiguration : IMyCustomConfiguration
        {
            public string GetMyCustomMessage()
            {
                return "This is from the My Custom Configuration class!";
            }
        }
    }
    
  5. Back in the Startup.cs class, we need to register the new service, so that the new class can be injected into the Startup method. This is done in the ConfigurationServices method:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IMyCustomConfiguration, MyCustomConfiguration>();
    }
    
  6. Registered services may have different service lifetimes. In this case, our configuration is a one-off Singleton class that can be used for the entire life of the application. The application only needs one class, so it is registered as a Singleton.
  7. Now the Custom Service can be injected into the Startup class, as follows:
    public void Configure(IApplicationBuilder app,
                                  IHostingEnvironment env,
                                  ILoggerFactory loggerFactory,
                                  IMyCustomConfiguration myCustomConfiguration)
            {
    

    Notice the IMyCustomConfiguration line has been added to the Configuration method. ASP.Net Core will see the interface and know to look up the list of services available for the IMyCustomConfiguration service. If it gets a match, it will inject the service into the class at runtime.

  8. By the way, there are many services already loaded by default in the environment. They are already loaded by the time the ConfigureServices method is run. In that method, you are simply adding to the pre-existing list of services.
  9. Next, we don’t need the Configuration line any more. That will be moved into the MyCustomConfiguration.cs file. Then we simply reference the new interface from within the code. The app.Run method now looks like this:
    public void Configure(IApplicationBuilder app,
                          IHostingEnvironment env,
                          ILoggerFactory loggerFactory,
                          IMyCustomConfiguration myCustomConfiguration)
    {
        loggerFactory.AddConsole();
    
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.Run(async (context) =>
        {
           //var myCustomMessage = Configuration["my-custom-message"];
           var newHelloWorldMessage = string.Format("Hello World! Your text was >{0}<", myCustomConfiguration.GetMyCustomMessage());
           await context.Response.WriteAsync(newHelloWorldMessage);
        });
    }
    
  10. If you run it now (F5), you should see the following message:
    “Hello World! Your text was >This is from the My Custom Configuration class!<“
  11. I now want to replace the message in the MyConfigurationClass.cs file with the one from the mycustomsettings.json file. This will also be done via dependency injection. We will inject the Configuration object into the MyCustomConfiguration class, but first we need to register the service.
  12. To be able to inject the Configuration service, we need to add it as a service. Again, we modify the ConfigurationServices method, as follows:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(provider =&gt; Configuration);
        services.AddSingleton&lt;IMyCustomConfiguration, MyCustomConfiguration&gt;();
    }
    

    Notice the lambda expression? That’s because we already have an instance of the Configuration object that we want. All we need to do is return it. This little trick neatly allows us to do that.

  13. To inject the configuration we follow the standard injection pattern. That involves adding a constructor to the class we want to inject it into, adding the service interface, and allowing the runtime to inject the service.
    namespace MyFirstAspNetCoreApp.Services
    {
        public interface IMyCustomConfiguration
        {
            string GetMyCustomMessage();
        }
    
        public class MyCustomConfiguration : IMyCustomConfiguration
        {
            private string myCustomMessage;
    
            public MyCustomConfiguration(IConfiguration configuration)
            {
                myCustomMessage = configuration[&quot;my-custom-message&quot;];
            }
    
            public string GetMyCustomMessage()
            {
                //return &quot;This is from the My Custom Configuration class!&quot;;
                return myCustomMessage;
            }
        }
    }
    

    Note the constructor that I’ve added to the class, which takes the IConfiguration service variable (line 12), which we have registered in the ConfigureServices method of the Startup.cs class. This sets the private variable myCustomMessage (line 10) to the string loaded from the JSON file. This is then used in the GetMyCustomMessage method (line 20) to return the configuration string to the app.Run method.

  14. Finally, run the application again, and you should see the message injected into the page, as follows:
    “Hello World! Your text was >The quick brown fox!<“

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: