在 Moq 中使用 AutoFac 属性注入 [英] Using AutoFac Property Injection with Moq

查看:98
本文介绍了在 Moq 中使用 AutoFac 属性注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下类:

public class ViewModelBase
{
    public IService Service { get; protected set; }
}

和这个班级的测试:

using var mock = AutoMock.GetLoose();
var viewModelBase = mock.Create<ViewModelBase>();
Assert.NotNull(viewModelBase.Service);

在我的普通应用程序中,我使用 Autofac.Core.NonPublicProperty 的属性注入功能将 IService 依赖项自动连接到 ViewModelBase>:

In my normal application, I'm using the property injection functionality of Autofac.Core.NonPublicProperty to autowire the IService dependency into the ViewModelBase:

containerBuilder.RegisterType(typeof(ViewModelBase)).AutoWireNonPublicProperties();

在测试中,我使用 Autofac.Extras.Moq 集成包来自动模拟 ViewModelBase 的依赖项.但是,据我所知,Autofac.Extras.Moq 仅支持构造函数注入.这会导致测试失败,因为 Service 属性不是由 Moq 自动装配的.

In the test, I'm using the Autofac.Extras.Moq integration package to automatically mock dependencies for ViewModelBase. However, as far as I can tell, only constructor injection is supported by Autofac.Extras.Moq. This causes the test to fail because the Service property is not autowired by Moq.

有没有什么优雅的方式来利用 AutoFac 和 Moq 的属性注入功能?

Is there any elegant way of utilizing the property injection function of AutoFac with Moq?

推荐答案

Autofac.Extras.Moq 仅支持构造函数注入

only constructor injection is supported by Autofac.Extras.Moq

实际上你是对的,但是 AutoMock.GetLoose 有一个重载,你可以通过传递一个 的委托来向模拟注入一个功能齐全的 IContainerContainerBuilder 具有所有常规的 autofac 功能:

Actually you are right, but the AutoMock.GetLoose has an overload in which you can inject to the mock a fully functioned IContainer by passing a delegate of ContainerBuilder with all the regular autofac features:

public class AutoMock : IDisposable
{
    //...  
    public IContainer Container { get; }
    public static AutoMock GetLoose(Action<ContainerBuilder> beforeBuild);
    //...
}

在您的情况下,扩展 Autofac.Extras.Moq 不支持 PropertiesAutowired() 方法,因此我们可以构建一个 ContainerBuilder 并使用委托传递它:

In your case the extension Autofac.Extras.Moq is not supporting the PropertiesAutowired() method so we can build a ContainerBuilder and pass it with a delegate:

Action<ContainerBuilder> containerBuilderAction = delegate(ContainerBuilder cb)
{
    cb.RegisterType<ServiceFoo>().As<IService>();
    cb.RegisterType<ViewModelBase>().PropertiesAutowired(); //The autofac will go to every single property and try to resolve it.
};

var mock = AutoMock.GetLoose(containerBuilderAction);
        
var viewModelBase = mock.Create<ViewModelBase>();            
Assert.IsNotNull(viewModelBase.Service);

IServiceServiceFoo实现类:

public class ServiceFoo : IService` { }

这篇关于在 Moq 中使用 AutoFac 属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆