Can I access the full power of Autofac in UnitTests, using the Moq integration

為{幸葍}努か 提交于 2019-12-05 08:09:52

Some of the features, you've mentioned, can be used with AutoMock class and some won't make sense any more. With AutoMock we do not deal with ContainerBuilder class - this is for simplicity, we don't want to have to code all those registering instructions, but to only register the ones interesting for us. So from creation of AutoMock object with GetLoose or GetStrict method we deal only with built IContainer object ready to resolve things. Fortunately for us IContainer still allows us to extend its registration set, however Autofac won't support that with its convenient extension methods as they are built to work with ContainerBuilder object. This is perfectly reasonable because for Autofac perspective extending definitions on IContainer object is something uncommon. ContainerBuilder is supposed to handle registration and IContainer is supposed to handle resolving.

Here I will, as an example, present how with AutoMock we may use auto-wired properties functionality:

using (var mock = AutoMock.GetLoose())
{
    mock.Container.ComponentRegistry.Register(
        RegistrationBuilder
            .ForType<MyClass>()
            .PropertiesAutowired()
            .CreateRegistration<MyClass, ConcreteReflectionActivatorData, SingleRegistrationStyle>()
    );
}

As you see now we have to deal with all the ugliness of autofac internal code which normally is hidden by extension methods. PropertiesAutowired functionality may be easily used with AutoMock, however lamda registration will not make much sense any more. What lambda registration gives us is that object being registered in ContainerBuilder can depend on other registered object which will be resolved during building ContainerBuilder to IContainer so we do not need to care for the order of the registering instructions. Here we already have ready made IContainer and it won't be built again so such deffering of registration is pointless. If we want to pass to some registered object another already registered object then we may simply resolve it first and then use it.

So as summary:

  • autofac features are generally accessible with AutoMock
  • some of the features are not available due to constraints of not registering things in ContainerBuilder but in IContainer object instead. Other stuff is probably not implemented yet and maybe will be delivered in future.
  • for almost all cases there are good workarounds as shown in the example above
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!