Asp.Net Core内蔵IOC容器の理解
3520 ワード
Asp.Net Core内蔵IOC容器の理解
01.IOC容器使用のメリット
02.実際の使用
1.コンソールプロジェクトを作成し、Nugetパッケージ参照Nugetパッケージを追加する:Microsoft.Extensions.DependencyInjection 2.単純な使用
class Program
{
static void Main(string[] args)
{
//
Bird bird = new Bird(); //IFly bird=new Bird();
bird.Fly();
//IOC
ServiceCollection serviceCollection = new ServiceCollection(); // IOC
serviceCollection.AddTransient(); //
var provider = serviceCollection.BuildServiceProvider(); // Provider
var fly = provider.GetService(); //
fly.Fly(); //
}
}
interface IFly
{
void Fly();
}
class Bird : IFly
{
public void Fly()
{
Console.WriteLine(" ........");
}
}
3.ログ登録
class Program
{
static void Main(string[] args)
{
ServiceCollection serviceCollection = new ServiceCollection();
//
serviceCollection.AddLogging(configure =>
configure.AddConsole()
);
serviceCollection.AddTransient();
var provider = serviceCollection.BuildServiceProvider();
provider.GetService();
var fly = provider.GetService();
fly.Fly();
}
}
interface IFly
{
void Fly();
}
class Bird : IFly
{
private readonly ILogger _iLogger;
public Bird(ILoggerFactory logger)
{
_iLogger = logger.CreateLogger();
}
public void Fly()
{
_iLogger.Log(LogLevel.Information, " .....");
Console.WriteLine(" ........");
}
}
4.ライフサイクル
AddScopedケースコード
class Program
{
static void Main(string[] args)
{
ServiceCollection serviceCollection = new ServiceCollection();
////
//serviceCollection.AddTransient();
//// ,
//serviceCollection.AddSingleton();
//
serviceCollection.AddScoped();
var provider = serviceCollection.BuildServiceProvider();
// scope
var scope1 = provider.CreateScope();
var scope2 = provider.CreateScope();
//
scope1.ServiceProvider.GetService();
//
scope2.ServiceProvider.GetService();
// :
var fly = provider.GetService();//
fly = provider.GetService();//
fly.Fly();
}
}
interface IFly
{
void Fly();
}
class Bird : IFly
{
public Bird()
{
Console.WriteLine(" ......");
}
public void Fly()
{
Console.WriteLine(" ........");
}
}
実行結果:三次構造関数が呼び出されました....