IoC容器Autofac使用入门(二)

Autofac的ServiceLocator模式应用,无配置

Program.cs代码如下:

 public class Program
    {
        static void Main(string[] args)
        {
            //初始化
            IocInitialize iocini = new IocInitialize();
            iocini.Initialize();

            //ServiceLocator模式应用
            for (int i = 0; i < 1000; i++)
            {
                //测试
                dosomething ds = new dosomething();
                ds.DoStuff();
            }
            Console.ReadLine();
        }
    }

IDependency,Interface1,Interface2接口:

/// <summary>
    /// 依赖注入接口,表示该接口的实现类将自动注册到IoC容器中
    /// </summary>
    public interface IDependency
    {
        void Select(string commandText);

        void Insert(string commandText);

        void Update(string commandText);

        void Delete(string commandText);
    }
  public interface Interface1 : IDependency
    {
        string console();
    }

    public interface Interface2 : IDependency
    {
        string write();
    }
IocInitialize.cs类代码:

 public class IocInitialize
    {
        /// <summary>
        /// 获取或设置 Autofac组合IContainer
        /// </summary>
        protected IContainer Container { get; set; }
        public IocInitialize()
        {
            ContainerBuilder builder = new ContainerBuilder();
            Container = builder.Build();
        }
        /// <summary>
        /// 依赖注入初始化
        /// </summary>
        public void Initialize()
        {
            Type baseType = typeof(IDependency);
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies().ToArray();//获取已加载到此应用程序域的执行上下文中的程序集。
            Type[] dependencyTypes = assemblies
                .SelectMany(s => s.GetTypes())
                .Where(p => baseType.IsAssignableFrom(p) && p != baseType).ToArray();//得到接口和实现类
            RegisterDependencyTypes(dependencyTypes);//第一步:注册类型
            SetResolver(assemblies);//第二步:
        }
       
        /// <summary>
        /// 实现依赖注入接口<see cref="IDependency"/>实现类型的注册
        /// </summary>
        /// <param name="types">要注册的类型集合</param>
        protected void RegisterDependencyTypes(Type[] types)
        {
            ContainerBuilder builder = new ContainerBuilder();
            var builderSource = builder.RegisterTypes(types)
                .AsSelf()
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();//PropertiesAutowired注册为属性注入类型,所有实现IDependency的注册为InstancePerLifetimeScope生命周期
            builder.Update(Container);
        }

        /// <summary>
        /// 设置CommonServiceLocator注册点
        /// </summary>
        /// <param name="assemblies"></param>
        protected void SetResolver(Assembly[] assemblies)
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.Update(Container);

            //IoC创建实例的四种模式:单例,每线程一实例,每调用一实例,每调用一实例(弱引用),当然你还可以扩展实例生命周期的管理策略。
            ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(Container));
        }
        
    }
dosomething.cs代码:

public class dosomething
    {
       public void DoStuff()
       {
           var service1 = ServiceLocator.Current.GetInstance<Interface1>();
           Console.WriteLine(service1.console());
           var service2 = ServiceLocator.Current.GetInstance<Interface2>();
           Console.WriteLine(service2.write());
       }
    }
Service1.cs,Service2.cs代码:

 public class Service1:Interface1
    {
        public string console()
        {
            return "这是接口1的实现!";
        }

        public void Select(string commandText)
        {
            throw new NotImplementedException();
        }

        public void Insert(string commandText)
        {
            throw new NotImplementedException();
        }

        public void Update(string commandText)
        {
            throw new NotImplementedException();
        }

        public void Delete(string commandText)
        {
            throw new NotImplementedException();
        }
    }

    public class Service2 : Interface2
    {

        public string write()
        {
            return "这是接口2的实现!";
        }

        public void Select(string commandText)
        {
            throw new NotImplementedException();
        }

        public void Insert(string commandText)
        {
            throw new NotImplementedException();
        }

        public void Update(string commandText)
        {
            throw new NotImplementedException();
        }

        public void Delete(string commandText)
        {
            throw new NotImplementedException();
        }
    }

创建实例方法

1InstancePerDependency

对每一个依赖或每一次调用创建一个新的唯一的实例。这也是默认的创建实例的方式。

官方文档解释:Configure the component so that every dependent component or call to Resolve() gets a new, unique instance (default.)

2InstancePerLifetimeScope

在一个生命周期域中,每一个依赖或调用创建一个单一的共享的实例,且每一个不同的生命周期域,实例是唯一的,不共享的。

官方文档解释:Configure the component so that every dependent component or call to Resolve() within a single ILifetimeScope gets the same, shared instance. Dependent components in different lifetime scopes will get different instances.

3InstancePerMatchingLifetimeScope

在一个做标识的生命周期域中,每一个依赖或调用创建一个单一的共享的实例。打了标识了的生命周期域中的子标识域中可以共享父级域中的实例。若在整个继承层次中没有找到打标识的生命周期域,则会抛出异常:DependencyResolutionException

官方文档解释:Configure the component so that every dependent component or call to Resolve() within a ILifetimeScope tagged with any of the provided tags value gets the same, shared instance. Dependent components in lifetime scopes that are children of the tagged scope will share the parent's instance. If no appropriately tagged scope can be found in the hierarchy an DependencyResolutionException is thrown.

4InstancePerOwned

在一个生命周期域中所拥有的实例创建的生命周期中,每一个依赖组件或调用Resolve()方法创建一个单一的共享的实例,并且子生命周期域共享父生命周期域中的实例。若在继承层级中没有发现合适的拥有子实例的生命周期域,则抛出异常:DependencyResolutionException

官方文档解释:

Configure the component so that every dependent component or call to Resolve() within a ILifetimeScope created by an owned instance gets the same, shared instance. Dependent components in lifetime scopes that are children of the owned instance scope will share the parent's instance. If no appropriate owned instance scope can be found in the hierarchy an DependencyResolutionException is thrown.

5SingleInstance

每一次依赖组件或调用Resolve()方法都会得到一个相同的共享的实例。其实就是单例模式。

官方文档解释:Configure the component so that every dependent component or call to Resolve() gets the same, shared instance.

6InstancePerHttpRequest

在一次Http请求上下文中,共享一个组件实例。仅适用于asp.net mvc开发。


结果如图:



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值