Pulse7
7/26/2017 - 10:10 PM

add config json and inject it, dependency injection

add config json and inject it, dependency injection

public IConfiguration Configuration{ get; set; }

public Startup()
        {
            Configuration = new ConfigurationBuilder().AddJsonFile("config.json").AddEnvironmentVariables().Build();
        }
        
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IGreetingService>(serv=> new GreetingService(Configuration));
        }
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
      <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
  </ItemGroup>
  <ItemGroup>
    <Content Update="config.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

</Project>
public class GreetingMessage
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }

    public interface IGreetingService
    {
        GreetingMessage GetTodayGreeting();
    }

    public class GreetingService : IGreetingService
    {
        private int _id=1;
        private IConfiguration _config;

        public GreetingService(IConfiguration config)
        {
            _config = config;
        }

        public GreetingMessage GetTodayGreeting()
        {
            return new GreetingMessage() {
                Id = _id++,
                Text = _config.GetValue<string>("message")
            };
        }
    }