zoukankan      html  css  js  c++  java
  • .NetCore IOC容器练习

    Microsoft.Extensions.DependencyInjection

    //添加Nuget包Microsoft.Extensions.DependencyInjection
    var serviceCollection = new ServiceCollection();
    serviceCollection.AddTransient<IBase, TheyClass>();
    serviceCollection.AddSingleton<IBase, MyClass>();
    serviceCollection.AddScoped<IBase, YouClass>();
    
    var serviceProvider = serviceCollection.BuildServiceProvider();
    serviceProvider.GetService<IBase>().SayHello();
    foreach (var item in serviceProvider.GetServices<IBase>())
    {
        item.SayHello();
    }
    serviceProvider.GetService<IBase>().SayHello();
    foreach (var item in serviceProvider.GetServices<IBase>())
    {
        item.SayHello();
    }
    //仅注册过的方可拿到,此处MyClass未注册,GetService为Null,抛异常
    serviceProvider.GetService<MyClass>().SayHello();
    //仅注册过的方可拿到,此处MyClass未注册,GetRequiredService提示未注册,抛异常
    serviceProvider.GetRequiredService<MyClass>().SayHello();

    Castle.Windsor:

    //需要添加Nuget包:Castle.Windsor.MsDependencyInjection和Castle.Core
    //需要添加引用:Castle.Windsor和Castle.Windsor.MsDependencyInjection
    //创建容器
    Castle.Windsor.WindsorContainer container = new Castle.Windsor.WindsorContainer();
    //旧版可以适用如下注册container.AddComponent<IBase, MyClass>();
    //容器注册组件,并且管理组件的生命周期
    container.Register(Component.For<IBase>().ImplementedBy<MyClass>().LifestyleSingleton().Named("MyClass"));
    container.Register(Component.For<IBase>().ImplementedBy<YouClass>().LifestyleScoped().Named("YouClass"));
    container.Register(Component.For<IBase>().ImplementedBy<TheyClass>().LifestyleTransient().Named("TheyClass"));
    container.BeginScope();
    //组件激活,拿到组件实例
    container.Resolve<IBase>("MyClass").SayHello();
    //声明周期为Scoped的,必须执行BeginScoped后开始调用,在下一个BeginScope调用之前,只实例化一次
    container.BeginScope();
    foreach (var item in container.ResolveAll<IBase>())
    {
        item.SayHello();
    }
    container.Resolve<IBase>("YouClass").SayHello();
    //声明周期为Scoped的,必须执行BeginScoped后开始调用,在下一个BeginScope调用之前,只实例化一次
    container.BeginScope();
    foreach (var item in container.ResolveAll<IBase>())
    {
        item.SayHello();
    }
    //容器释放
    container.Dispose();
  • 相关阅读:
    第一节 Spring的环境搭建
    002. 配置环境变量
    001. 巧妇难为无米之炊之安装环境
    第七节 认识SpringMVC中的表单标签
    [六字真言]6.吽.SpringMVC中上传大小异常填坑
    [六字真言]4.叭.SpringMVC异常痛苦
    [六字真言]5.咪.功力不足,学习前端JavaScript异常
    [六字真言]3.呢.异常的谎言,你要相信多少次?
    [六字真言]2.嘛.异常定制和通用.md
    vim基本技巧
  • 原文地址:https://www.cnblogs.com/lcawen/p/12888580.html
Copyright © 2011-2022 走看看