首頁  >  文章  >  後端開發  >  經典的IoC/DI容器--StructureMap

經典的IoC/DI容器--StructureMap

零下一度
零下一度原創
2017-06-23 15:59:022080瀏覽

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的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn