、受け入れ答えに触発さ:
Program.csの
public class Program
{
public static void Main(string[] args)
{
IServiceCollection services = new ServiceCollection();
// Startup.cs finally :)
Startup startup = new Startup();
startup.ConfigureServices(services);
IServiceProvider serviceProvider = services.BuildServiceProvider();
//configure console logging
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug);
var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
logger.LogDebug("Logger is working!");
// Get Service and call method
var service = serviceProvider.GetService<IMyService>();
service.MyServiceMethod();
}
}
Startup.cs
public class Startup
{
IConfigurationRoot Configuration { get; }
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddSingleton<IConfigurationRoot>(Configuration);
services.AddSingleton<IMyService, MyService>();
}
}
appsettings.jsonここでガイドです
{
"SomeConfigItem": {
"Token": "8201342s223u2uj328",
"BaseUrl": "http://localhost:5000"
}
}
MyService.cs
public class MyService : IMyService
{
private readonly string _baseUrl;
private readonly string _token;
private readonly ILogger<MyService> _logger;
public MyService(ILoggerFactory loggerFactory, IConfigurationRoot config)
{
var baseUrl = config["SomeConfigItem:BaseUrl"];
var token = config["SomeConfigItem:Token"];
_baseUrl = baseUrl;
_token = token;
_logger = loggerFactory.CreateLogger<MyService>();
}
public async Task MyServiceMethod()
{
_logger.LogDebug(_baseUrl);
_logger.LogDebug(_token);
}
}
IMyService.cs
public interface IMyService
{
Task MyServiceMethod();
}
あなたが達成するために何をしようとしていますか? Webページを提供できるコンソールアプリケーションですか?はい、それは "自己完結型asp.netコアアプリケーション"であり、利用可能ないくつかの例があります。 http://druss.co/2016/08/deploy-and-run-net-core-application-without-installed-runtime-self-contained-applications/ –
@ArashMotamedi私はASP.NETアプリケーションをホストしたくありません。私はクラスライブラリプロジェクトを開始する良い古いコンソールアプリケーションを持っていたい。私は、私がDependency Injectionなどを無料で入手できると思った。 – Daniel
入手しました。しかし、はい、あなたのアプローチは少し後ろです。すべての.netコアアプリケーションは独立したライブラリで構成されているので、任意のプロジェクトタイプのライブラリを自由に参照することができます。 Asp.netのコアアプリケーションは、多くのライブラリを参照するようにあらかじめ設定されており、httpエンドポイントを公開しています。しかし、あなたがあなたのコンソールアプリケーションに必要なDependency Injectionなら、適切なライブラリを参照するだけです。ここにガイドがあります:http://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/ –