Provider is not a pattern by Mark Seemann

来源:互联网 发布:js 判断对象类型 编辑:程序博客网 时间:2024/04/27 21:10

Developers exposed to ASP.NET are likely to be familiar with the so-called Provider pattern. You see it a lot in that part of the BCL: Role Provider, Membership Provider, Profile Provider, etc. Lots of text has already been written about Providers, but the reason I want to add yet another blog post on the topic is because once in a while I get the question on how it relates to Dependency Injection (DI).

Is Provider a proper way to do DI?

No, it has nothing to do with DI, but as it tries to mimic loose coupling I can understand the confusion.

First things first. Let’s start with the name. Is it a pattern at all? Regular readers of this blog may get the impression that I’m fond of calling everything and the kitchen sink an anti-pattern. That’s not true because I only make that claim when I’m certain I can hold that position, so I’m not going to denounce Provider as an anti-pattern. On the contrary I will make the claim that Provider is not a pattern at all.

A design pattern is not invented - it’s discovered as a repeated solution to a commonly recurring problem. Providers, on the other hand, were invented by Microsoft, and I’ve rarely seen them used outside their original scope. Secondly I’d also dispute that they solve anything.

That aside, however, I want to explain why Provider is bad design:

  1. It uses the Constrained Construction anti-pattern
  2. It hides complexity
  3. It prevents proper lifetime management
  4. It’s not testable

In the rest of this post I will explain each point in detail, but before I do that we need an example to look at. The old OrderProcessor example suffices, but instead of injecting IOrderValidator, IOrderCollector, and IOrderShipper this variation uses Providers to provide instances of the Services:

public SuccessResult Process(Order order){    IOrderValidator validator =         ValidatorProvider.Validator;    bool isValid = validator.Validate(order);    if (isValid)    {        CollectorProvider.Collector.Collect(order);        ShipperProvider.Shipper.Ship(order);    }    return this.CreateStatus(isValid);}

The ValidatorProvider uses the configuration system to create and return an instance of IOrderValidator:

public static IOrderValidator Validator{    get     {        var section =             OrderValidationConfigurationSection                .GetSection();        var typeName = section.ValidatorTypeName;        var type = Type.GetType(typeName, true);        var obj = Activator.CreateInstance(type);        return (IOrderValidator)obj;    }}

There are lots of details I omitted here. I could have saved the reference for later use instead of creating a new instance each time the property is accessed. In that case I would also have had to make the code thread-safe, so I decided to skip that complexity. The code could also be more defensive, but I’m sure you get the picture.

The type name is defined in the app.config file like this:

<orderValidation   type="Ploeh.Samples.OrderModel.UnitTest.TrueOrderValidator,        Ploeh.Samples.OrderModel.UnitTest" />Obviously, CollectorProvider and ShipperProvider follow the same… blueprint.

This should be well-known to most .NET developers, so what’s wrong with this model?

Constrained Construction

In my book’s chapter on DI anti-patterns I describe the Constrained Construction anti-pattern. Basically it occurs every time there’s an implicit constraint on the constructor of an implementer. In the case of Providers the constraint is that each implementer must have a default constructor. In the example the culprit is this line of code:

var obj = Activator.CreateInstance(type);

This constrains any implementation of IOrderValidator to have a default constructor, which obviously means that the most fundamental DI pattern Constructor Injection is out of the question.

Variations of the Provider idiom is to supply an Initialize method with a context, but this creates a temporal coupling while still not enabling us to inject arbitrary Services into our implementations. I’m not going to repeat six pages of detailed description of Constrained Construction here, but the bottom line is that you can’t fix it - you have to refactor towards true DI - preferably Constructor Injection.

Hidden complexity

Providers hide the complexity of their implementations. This is not the same as encapsulation. Rather it’s a dishonest API and the problem is that it just postpones the moment when you discover how complex the implementation really is.

When you implement a client and use code like the following everything looks deceptively simple:

IOrderValidator validator = ValidatorProvider.Validator;

However, if this is the only line of code you write it will fail, but you will not notice until run-time. Check back to the implementation of the Validator property if you need to refresh the implementation: there’s a lot of things that can go wrong here:

The appropriate configuration section is not available in the app.config file.
The ValidatorTypeName is not provided, or is null, or is malformed.
The ValidatorTypeName is correctly formed, but the type in question cannot be located by Fusion.
The Type doesn’t have a default constructor. This is one of the other problems of Constrained Construction: it can’t be statically enforced because a constructor is not part of an abstraction’s API.
The created type doesn’t implement IOrderValidator.
I’m sure I even forgot a thing or two, but the above list is sufficient for me. None of these problems are caught by the compiler, so you don’t discover these issues until you run an integration test. So much for rapid feedback.

**I don’t like APIs that lie about their complexity.
Hiding complexity does not make an API easier to use; it makes it harder.
An API that hides necessary complexity makes it impossible to discover problems at compile time. It simply creates more friction.**

Lifetime management issues

A Provider exerts too much control over the instances it creates. This is a variation of the Control Freak anti-pattern (also from my book). In the current implementation the Validator property totally violates the Principle of least surprise since it returns a new instance every time you invoke the getter. I did this to keep the implementation simple (this is, after all, example code), but a more normal implementation would reuse the same instance every time.

However, reusing the same instance every time may be problematic in a multi-threaded context (such as a web application) because you’ll need to make sure that the implementation is thread-safe. Often, we’d much prefer to scope the lifetime of the Service to each HTTP request.

HTTP request scoping can be built into the Provider, but then it would only work in web applications. That’s not very flexible.

What’s even more problematic is that once we move away from the Singleton lifestyle (not to be confused with the Singleton design pattern) we may have a memory leak at hand, since the implementation may implement IDisposable. This can be solved by adding a Release method to each Provider, but now we are moving so far into DI Container territory that I find it far more reasonable to just use proper DI instead of trying to reinvent the wheel.

Furthermore, the fact that each Provider owns the lifetime of the Service it controls makes it impossible to share resources. What if the implementation we want to use implements several Role Interfaces each served up by a different Provider? We might want to use that common implementation to share or coordinate state across different Services, but that’s not possible because we can’t share an instance across multiple providers.

Even if we configure all Providers with the same concrete class, each will instantiate and serve its own separate instance.

Testability

The Control Freak also impacts testability. Since a Provider creates instances of interfaces based on XML configuration and Activator.CreateInstance, there’s no way to inject a dynamic mock.

It is possible to use hard-coded Test Doubles such as Stubs or Fakes because we can configure the XML with their type names, but even a Spy is problematic because we’ll rarely have an object reference to the Test Double.

In short, the Provider idiom is not a good approach to loose coupling. Although Microsoft uses it in some of their products, it only leads to problems, so there’s no reason to mimic it. Instead, use Constructor Injection to create loosely coupled components and wire them in the application’s Composition Root using the Register Resolve Release pattern.

0 0
原创粉丝点击