经典的IoCDI容器--StructureMap

经典的IoCDI容器--StructureMap,第1张

经典的IoC/DI容器--StructureMap StructureMap是一款很老的IoC/DI容器,从2004年.NET 1.1支持至今。

一个使用例子
    //创建业务接口
    public interface IDispatchService { }
    public interface ICourier { }
    public interface IPaymentGateway { }
    public interface IPaymentMerchant { }

    //接口的实现
    public class DispacthService : IDispatchService
    {
        private ICourier _courier;
        public DispacthService(ICourier courier)
        {
            _courier = courier;
        }
        public override string ToString()
        {
            return _courier.ToString();
        }
    }
    public class FedExCourier : ICourier { }
    public class StreamLinePaymentMerchant : IPaymentMerchant { }
    public class PaymentGateway : IPaymentGateway
    {
        private IPaymentMerchant _paymentMerchant;
        public PaymentGateway(IPaymentMerchant paymentMerchant)
        {
            _paymentMerchant = paymentMerchant;
        }
        public override string ToString()
        {
            return _paymentMerchant.ToString();
        }
    }

    //业务使用
    public class OrderService
    {
        private IPaymentGateway _paymentGateway;
        private IDispatchService _dispacthService;

        public OrderService(IPaymentGateway paymentGateway, IDispatchService dispacthService)
        {
            _paymentGateway = paymentGateway;
            _dispacthService = dispacthService;
        }
        public override string ToString()
        {
            return string.Format("IPaymentGateway:{0}  IDispatchService:{1}", _paymentGateway.ToString(), _dispacthService.ToString());
        }
    }

    //配置依赖关系
    public class BootStrapper
    {
        public static void ConfigureStructureMap()
        {
            ObjectFactory.Initialize(x => x.AddRegistry<ModelRegistry>());
        }
    }

    public class ModelRegistry : Registry
    {
        public ModelRegistry()
        {
            For<IPaymentGateway>().Use<PaymentGateway>();
            For<IPaymentMerchant>().Use<StreamLinePaymentMerchant>();
            For<IDispatchService>().Use<DispacthService>();
            For<ICourier>().Use<FedExCourier>();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            BootStrapper.ConfigureStructureMap();//启用配置


            OrderService orderService = ObjectFactory.GetInstance<OrderService>();
            Console.WriteLine(orderService.ToString());

            IPaymentGateway paymentGateway= ObjectFactory.GetInstance<PaymentGateway>();
            Console.WriteLine(paymentGateway);

            Console.ReadKey();
        }
    }

以上就是经典的IoC/DI容器--StructureMap的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/684494.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存