科技动态

ServiceConfiguration attribute considered harmful

微信扫一扫,分享到朋友圈

ServiceConfiguration attribute considered harmful

When working with Episerver, there are several ways how to register your classes in an IoC container. You can choose between StructureMap’s configuration API, Episerver’s configuration API or use Episerver’s ServiceConfiguration attribute on your class.

There are several issues when using ServiceConfiguration
attribute. Yes, it is easier just to add an attribute to your class and forget about its registration in an IoC container. But this is the only benefit you get.

Lifecycle management

When using ServiceConfiguration
attribute, the lifecycle of a service is determined before the composition of an object graph. This might lead to weird bugs in the code. For example, some service might be configured as a singleton (with ServiceConfiguration attribute), and it depends on another service.

[ServiceConfiguration(ServiceType = typeof(IService), Lifecycle = ServiceInstanceScope.Singleton)]
public class MyService : IService
{
    private IDependency _dependency;

    public MyService(IDependency dependency)
    {
        _dependency = dependency;
    }

    public void Execute()
    {
        _dependency.Run();
    }
}

At this time, you might not know what lifecycle your dependency has. If it is a singleton, then it is okay. But if the dependency is transient, you might get weird results.

Deferring lifecycle management for later – in the composition root or IoC container configuration, allows you to make these decisions when you see the whole picture – all components you have to compose. It is easier with Poor DI
to find lifecycle incompatibilities as a compiler will not allow you even to compile the wrong composition. With IoC
containers and their configuration API it is harder, but at least the configuration is in one place.

Single Responsibility Principle (SRP)

As of single responsibility principle, your code should not have more than one reason to change. With ServiceConfiguration attribute you add another reason – lifecycle management and IoC configuration. IoC configuration leaks into your code. If you would like to reuse your class outside of Episerver
code, you would need to modify it.

Summary

Unfortunately, Episerver’s documentation
describes ServiceConfiguration
as a first example ( Implicit registration of services
).

I suggest you always to use “Explicit registration of services.” Create an IConfigurableModule
module and register your services. You also might want to use StructureMap
configuration instead. It would give you more options and more flexibility by splitting different configs into separate registry files.

日本将启用有独立意识的机器人女主播:画面亮眼

上一篇

36氪首发 | 让每家医院都能用上外科手术机器人,「华志微创」获5000万元首轮融资

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

ServiceConfiguration attribute considered harmful

长按储存图像,分享给朋友