经典的IoC/DI容器--StructureMap


本文摘自PHP中文网,作者零下一度,侵删。

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

一个使用例子

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

//创建业务接口

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的详细内容!

相关阅读 >>

经典的ioc/di容器--StructureMap

更多相关阅读请进入《StructureMap》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...