首页 > 解决方案 > Autofac.ILifetimeScope:无法模拟或解析我的服务类

问题描述

我在我的应用程序中为服务层创建了一个测试项目,一切正常,但我需要模拟我的一个服务类,它存在于其他文件夹或命名空间中,但解决方案相同。所以我尝试像下面那样模拟服务类(IEmailService),但是在调用“ResolveServiceInstance”函数时,它会转到“TearDown”(属性)方法来处理 Autofac.ILifetimeScope 的容器/对象。我不知道我哪里出错了,请帮我解决这个问题。

我模拟服务类的“设置”方法,

public ILifetimeScope Container { get; private set; }

[SetUp]
public void SetUpTest()
{
    MockPermissionService = new Mock<IPermissionService>();
    MockPermissionServiceProvider = new Mock<IPermissionServiceProvider>();
    MockPlatformEmailService = new Mock<Platform.Services.IEmailService>();
    Container = ServiceTestsSetUp.GlobalContainer.BeginLifetimeScope(builder =>
    {
        builder.Register(c => MockPermissionService.Object).As<IPermissionService>();
        builder.Register(c => MockPermissionServiceProvider.Object).As<IPermissionServiceProvider>();
        PreServiceResolve(builder);
    });

    Service = ResolveServiceInstance();
    AddStaticData();
} 

我的 ResolveServiceInstance 函数,

private TService ResolveServiceInstance()
{
   return Container.Resolve<TService>();
}

当它返回 container.Resolve 方法时,它会显示以下错误消息,因此我无法注册或模拟其他命名空间类。我在这里做错了什么?

 DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'InEight.Platform.Services.EmailService' can be invoked with the available services and parameters:
 Cannot resolve parameter 'InEight.Platform.TenantInfo tenant' of constructor 'Void .ctor(InEight.Platform.TenantInfo, InEight.Platform.Site.Services.Contexts.ICoreDataContext, InEight.Platform.Logs.IAppLog)'.    

标签: c#unit-testingmockingautofacteardown

解决方案


推荐阅读