Does Structuremap support Lazy out of the box?

前端 未结 2 2027
慢半拍i
慢半拍i 2021-01-11 17:58

Does structuremap allow you to do constructor injection in a lazy fashion? Meaning not creating the object which is injected until it is used?

2条回答
  •  我在风中等你
    2021-01-11 18:30

    Yes, it does. The latest version of StructureMap (2.6.x) is compiled against .NET Framework 3.5, and so does not have access to the Lazy type introduced in .NET 4. However, it does support the same functionality - "not creating the object which is injected until it is used". Instead of depending on a Lazy, you depend on a Func. No special container registration is required.

    I've included a sample program that creates the following output:

    Created Consumer
    Consuming
    Created Helper
    Helping
    

    Sample.cs:

    class Program
    {
        static void Main(string[] args)
        {
            var container = new Container(x =>
            {
                x.For().Use();
                x.For().Use();
            });
    
            var consumer = container.GetInstance();
            consumer.Consume();
        }
    }
    
    public class Consumer : IConsumer
    {
        private readonly Func _helper;
    
        public Consumer(Func helper)
        {
            _helper = helper;
            Console.WriteLine("Created Consumer");
        }
    
        public void Consume()
        {
            Console.WriteLine("Consuming");
            _helper().Help();
        }
    }
    
    public interface IConsumer
    {
        void Consume();
    }
    
    public interface IHelper
    {
        void Help();
    }
    
    public class Helper : IHelper
    {
        public Helper()
        {
            Console.WriteLine("Created Helper");
        }
    
        public void Help()
        {
            Console.WriteLine("Helping");
        }
    }
    

提交回复
热议问题