Пример #1
0
        public static void Main(string[] args)
        {
            // use a JSON configuration file to specify whether the output should to to the console or to the DB.
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();
            var outputLocation = configuration.GetSection("AppSettings:output_location");


            // Configure the dependency injection based on the setting in the config file.
            // There's only one HelloWorldService, but the "writer" object is injected into the
            // constructor using DI magic.
            var serviceProvider = new ServiceCollection()
                                  .AddTransient <IHelloWorldWriter>(s => {
                IHelloWorldWriter writer;
                if (outputLocation.Value == "console")      //constants might be nice here, but this is just for pretend.
                {
                    writer = new HelloWorldConsoleWriter();
                }
                else if (outputLocation.Value == "sql")
                {
                    writer = new HelloWorldSqlWriter();
                }
                else
                {
                    throw new ApplicationException("Undefined output type");
                }
                return(writer);
            })
                                  .AddTransient <IHelloWorldService, HelloWorldService>()
                                  .BuildServiceProvider();

            // if the configuration file is changed to output_location = "sql", a NotImplementedException is thrown
            var helloWorld = serviceProvider.GetService <IHelloWorldService>();

            helloWorld.WriteHelloWorld();
        }
Пример #2
0
        public void HelloWorldTest_DoesSQLThrowError()
        {
            var sqlWriter = new HelloWorldSqlWriter();

            Assert.ThrowsException <NotImplementedException>(() => sqlWriter.WriteHelloWorld());
        }