AutoSubstitute Provide()-Autofac容器

时间:2019-03-15 07:43:51

标签: c# autofac nsubstitute automocking

使用AutoSubstitute库中的AutofacContrib.NSubstitute,我想将AutoSubstitute中的容器实例传递给由AutoSubstitute解析的类。尽管尽管IContainer是通过AutoSubstitute.Provide()方法设置的,但并不是希望通过构造函数将IContainer实例传递给SomeAppClass的方法。

using System;
using Autofac;
using AutofacContrib.NSubstitute;

namespace NSubstituteTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var autoSubstitute = new AutoSubstitute();

            autoSubstitute.Provide<IContainer>(autoSubstitute.Container);

            autoSubstitute.Resolve<SomeAppClass>();

            Console.Read();
        }
    }

    public class SomeAppClass
    {
        private readonly IContainer _container;
        private readonly ITestClass _testClass;

        // The IContainer instance should be the autoSubstitute.Container set on line 13 using the Provide() method
        public SomeAppClass(IContainer container)
        {
            _container = container;

            // Error thrown when trying to retrieve an automocked instance for ITestClass
            _testClass = _container.Resolve<ITestClass>();
        }
    }

    public interface ITestClass
    {
        void TestMethod();
    }
}

0 个答案:

没有答案