Transferring ownership of an IDisposable object and the builder design pattern - c#

I'm used to the approach when it is the object that creates another object (either directly or through factories, builders, etc) - is the one that "owns" it, thus manages its lifetime.
This idea works fine in almost every case.
But sometimes the one that creates an object simply cannot manage it, for instance in the builder design pattern implementation:
IFoo BuildFoo()
{
var dep = new Dep();
return new Foo(dep);
}
So, here the builder cannot manage the lifetime of the dep object since:
it does not have a reference to it;
it does not know when it is safe to Dispose it.
The naive solution would be to make Foo : IDisposable and let it manage the Dep passed to its constructor.
But then another dilemma arises:
using (var dep = new Dep())
{
using (var foo = new Foo(dep))
{
// (1) do something with foo
}
// (2) !!! do something with dep !!!
}
The code above becomes unsafe: at the point (2) it's not safe to use dep since it is already Disposed by foo.
And there is nothing syntactically that can denote, whose responsibility it is to manage the lifetime of an object.
So the question: what would be a general solution for that?

In this case, I wouldn't worry about it. I'm going to get shot to pieces here, I imagine, but "builders", "factories" etc are all places where I think it's okay to create an object and hand off it's disposal to the thing that asked for it.
There is a rule though that the builder/factory must only be creating the object, and not doing anything with it.
Of course, if you're newing-up objects using the new keyword, then you're coupling yourself to that implementation (even if it's indirectly via a factory class). You might want instead to consider dependency injection, depending on what the created objects are for, in which case a DI container would create the objects and dispose them for you at the correct time, based on their configured lifestyle.

very naive implementation
void Main()
{
using (var builder = new Builder())
{
var foo = builder.Create();
// do smtg
}
}
public class Foo
{
public Foo(Dep instance)
{
}
}
public class Dep : IDisposable
{
public void Dispose()
{
Console.WriteLine($"{this.GetType().Name} disposed!");
}
}
public class Builder : IDisposable
{
private List<IDisposable> _disposables = new List<System.IDisposable>();
public Foo Create()
{
var dep = new Dep();
_disposables.Add(dep);
var foo = new Foo(dep);
return foo;
}
public void Dispose()
{
foreach(var d in _disposables)
d.Dispose();
Console.WriteLine($"{this.GetType().Name} disposed!");
}
}
If something owns IDisposable, then it should implement IDisposable.
And, ofcourse, this is very naive impl, just as sample.

What about you let Foo call the builder to instantiate Dep and use it whenever it needs to. This way Foo manages the lifetime of Dep without the client of Foo having to worry about it.

Related

StructureMap - Circular Dependencies and Lazy Initialization of Setter Properties

So we have ran into what seems like a very common issue with StructureMap and IoC containers in general I assume. Bidirectiona/Circuar dependencies.
Given the following code, it is currently causing a circular dependency since we have it 'autowiring' properties.
public class ServiceA:IServiceA
{
public IServiceB ServiceBDependency {get;set;}
}
public class ServiceB:IServiceB
{
public IServiceA ServiceADependency {get;set;}
}
I see the 'dependency' of each of these on eachother, however, I feel that as a property, they are not true dependencies which is what separates them from using constructor injection.
It seems that there should be a way for these services to be resolved...and then have the properties injected after the objects have been created?
I know of various ways to get around this, including the true clean way of rearchitecting my services, but i am curious as to what options I have with instantiation and service registration with StructureMap. It seems like a fairly common issue that would need a solution.
I'd like to show you my approach. I am using only the setter injection. And we often have many objcets referencing each other, in our web app. E.g. IUserFacade requires IUserState on user creation while IUserState requires IUserFacade on userState deletion (to check for constraint).
e.g.:
public interface IUserFacade
{
... // User facade Add, Update, Delete
IUserStateFacade { set; }
}
public interface IUserStateFacade
{
...
IUserFacade { set; }
}
In reality, we have many objects with cross references, and even more complicated. And it would really be very costy, if all the referenced objects should be created each time, even if not used during the request. We need the "lazy", the proxy objects to be placed in the setters.
The way how to do it, is a mix of the: 1) StructureMap (IoC top) and 2) Castle (proxying top) libraries. Below I will show some snippets of objects needed for this solution. More could be found inside open source project Catharsis
Wrapper. This object would be injected into each Property by SM (StructureMap) instead of real implementor. It is the sleeping implementation. It is waiting for a first call. If it will never happen (IUserFacade is deleting user, no need to access referenced IUserStateFacade during such request) this wrapper will sleep for ever (request). Once touched, SM will create the real object and Wrapper will pass all calls to that.
The Castle interceptor:
public class Wrapper : IInterceptor
{
object _lazy;
protected readonly Type Type;
public Wrapper(Type type)
{
Type = type;
}
public void Intercept(IInvocation invocation)
{
if (_lazy.IsNull()) // lazily instantiate the instance
{
_lazy = ObjectFactory.GetInstance(Type);
}
try
{
var method = invocation.Method;
if (method.ContainsGenericParameters)
{
method = method.MakeGenericMethod(invocation.GenericArguments);
}
invocation.ReturnValue = method.Invoke(_lazy, invocation.Arguments);
}
catch (TargetInvocationException ex)
{
// PublishingManager.Publish(.... // publish exception
throw;
}
}
}
ProxyInstance. Now, we need an object, clear and understandable to SM. That object will be mapped to all interfaces (IUserFacade...) Instead of returning implementation of the UserFacade.
We can also use our custom AOP filters here.
This ProxyInstance will be provided with the real implementor type, and building up the Wrapper.
The StructureMap Instance:
public class ProxyInstance : Instance
{
protected readonly ProxyGenerator Factory = new ProxyGenerator();
protected readonly Type ConcreteType;
public ProxyInstance(Type type)
{
ConcreteType = type; // the type for our Wrapper, the real implementation
}
protected override object build(Type pluginType, BuildSession session)
{
var aopFilters =
// my custom way how to inject more AOP filters
AopFilterManager.GetFilters()
// the core for us, one of the interceptors is our Wrapper
.Union(new[] { new Wrapper(ConcreteType) })
.ToArray();
// Castle will emit a proxy for us, but the Wrapper will do the job
var proxy = Factory
.CreateClassProxy(ConcreteType, AopFilterManager.AopOptions, aopFilters);
return proxy;
}
And now just use some standard way how to map it in the SM (I am using custom ProxyConvention but it is out of the scope here). Let's use simplified explicit mapping:
registry
.For<IUserFacade>()
.HybridHttpOrThreadLocalScoped()
.Use(new ProxyInstance(typeof(UserFacade)));
...
Also, each of our objects created via SM, implements IService. So, the default setter injection could be set like this:
registry.SetAllProperties
(
set => set.TypeMatches
(
type => type
.GetInterfaces()
.Any(i => i.IsEquivalentTo(typeof(IService)))
)
);
From that moment, when we need to work with a IUserFacade (the direct ObjectFactory call, or accessed via Wrapper), we recieve the real implementor. All its properties (setter injection) will be pre-populated with our ProxyInstance / Wrapper.
If any of these properties is accessed, e.g. IUserStateFacade the same (discribed above for IUserFacade) will happen again.
Because the Lifecycle is Thread or Request based, we have only one implementor in runtime/web request
Because we do inject the Wrappers while using setter injection, no issues with circular infinite loops. Only the first level is injected each time

how to use Factory pattern? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Constructor vs. Factory in .NET Framework
I understand factory patten and have implemented it but couldn't get what benefit it will bring. For example instead of:
MyType1 obj=new Mytype1();
MyType2 obj=new Mytype2();
writing:
IMyType obj1 = Factory.Create(1);
IMyType obj2 = Factory.Create(2);
Is it something I have missed or not conceive. Can you please put your own experience example.
Some benefits of the factory pattern:
You can keep track of the objects you create. If you want to re-use objects or enforce a limit on the number of objects created, the factory can enforce that.
You can control how objects are created. If there are some parameters used to create the objects, you can return an existing object when clients pass in the same parameters for an object that has already been created.
You can have the factory return an interface but internally create different types of objects that support the interface.
Factory patterns are good for many reasons
A couple of them are:
you can initialise the item in the factory (default values etc) and make the item creation procedural (look at other classes/procedures, get defaults, inspect configuration values).
A constructor is one way to create an item but you can't inspect other classes or run other processes that are outside of the newly created instance without tightly coupling the class to these dependencies
it provides a central repository for item creation which enforces patterns/practices amongst developers in your team
Those are some of the reasons I can think of :)
e.g.
This class is dependent on the ConfigManager for instantiation
class SomeClass
{
public int SomeValue;
public SomeClass()
{
// Check the config for some value
SomeValue = ConfigManager.GetDefaultInt("SomeValue");
}
}
This class is not because it uses a factory
class SomeClass
{
public int SomeValue;
public SomeClass()
{
}
}
class SomeClassFactory
{
public SomeClass CreateSomeClass()
{
SomeClass obj = new SomeClass();
obj.SomeValue = ConfigManager.GetDefaultInt("SomeValue");
}
}
The benefit of the Factory pattern is that it encapsulates the details of construction and specific type from how it is used. This allows you to evolve to more interesting designs later with fewer places to make a change.
Consider this example:
public interface IStorage
{
void Save(SomeObject toSave);
SomeObject Get(SomeId id);
}
public class DatabaseStorage : IStorage
{
public void Save(SomeObject toSave)
{
//persist to DB somehow
}
public SomeObject Get(SomeId id)
{
//get from db somehow and return
}
}
public class StorageFactory
{
public IStorage GetStorage()
{
return new DatabaseStorage();
}
}
public class DatabaseStorage : IStorage
{
public void Save(SomeObject toSave)
{
//persist to DB somehow
}
public SomeObject Get(SomeId id)
{
//get from db somehow and return
}
}
Now imagine you later get the requirement to cache some results, or to log all results. You could create a proxy, like this:
public class LoggingStorage : IStorage
{
private readonly IStorage _proxied;
public LoggingStorage(IStorage proxied)
{
_proxied = proxied;
}
public void Save(SomeObject toSave)
{
//log this call
_proxied.Save(toSave);
}
public SomeObject Get(SomeId id)
{
//log this call
return _proxied.Get(id);
}
}
Now, if you used a constructor, you have to replace every use of it to wrap it with this. If you used the factory, you only change it:
public class StorageFactory
{
public IStorage GetStorage()
{
return new LoggingStorage(new DatabaseStorage());
}
}
Of course, speculative factories can seem a little heavy handed for this, which is why I prefer to encapsulate the constructor.
jQuery is a factory function that takes advantage of the way JavaScript works to create objects with a very low memory footprint.
Let's investigate with a horribly mutilated, drastically simplified version of jQuery to help see the potential benefits:
var $ = jQuery = (function(){ //this anon function fires once, and returns a function
//defines all kinds of internal functions jquery uses here
function jQuery(selector,context){ // we're going to return this inner JQ later
//defines only the logic needed to decide what to do with the arguments here
//and then builds the jQuery object with 'return new jQuery.prototype.init();'
}
//defines jQuery.prototype properties here:
jQuery.prototype = {
//...
init:function(selector,context){ //gets used to build the JQ objects
this.constructor.prototype = jQuery.prototype; //hands off the function prototype
}
//...
}
return jQuery; //this gets assigned to the outer jQuery and $ vars
})()
So... now we have a factory function that is also something like a namespace whose prototype we can extend, and expect those methods to be available on the object it spits out. Furthermore, the objects themselves have very little weight in memory aside from the DOM objects they typically wrap because all functions are references pulled in from closure or the outer prototype object that gets handed off as a reference. Aside from a bit of logic and some state vars, everything the object needs is built when jQuery first gets parsed or handed down from the prototype object as you add new methods to factory function's prototype property.
Now, try to do that with new jQuery()
If anything, applying the factory pattern in JavaScript can be immensely and uniquely powerful.

Does Funq support ResolveAll?

Does the Funq IoC container support resolving all registrations for a type? Something like either of these:
IEnumerable<IFoo> foos = container.Resolve<IEnumerable<IFoo>>();
IEnumerable<IFoo> foos = container.ResolveAll<IFoo>();
Funq does not have a ResolveAll method, but you can simply register an IEnumerable<IFoo> and resolve it with Resolve<IEnumerable<IFoo>>() as you show in your question.
In general however, it is better not to request the container for collections, but use composites instead. This way you can simply inject an IFoo as a dependency, instead of forcing consumers of that dependency to iterate the list. Instead you embed the code that loops the list of IFoo instances inside the composite. This keeps your code DRY and doesn't force you to go through the (possible) dozens of foreach (var foo in foos) statements scattered throughout the application, when a change has to be made in the way the items are iterated. Or let me put it in an other way: it is not the responsibility of a consumer to know how to iterate all IFoos.
Here is an example of an IFoo Composite:
// A composite is something that implements an interface
// (in this case IFoo) and wraps a list of items of that
// same interface.
public class FooComposite : IFoo
{
private readonly IEnumerable<IFoo> foos;
public FooComposite(params IFoo[] foos)
{
this.foos = foos;
}
void IFoo.FooThatThing(IBar bar)
{
foreach (var foo in this.foos)
{
foo.FooThatThing(bar);
}
}
}
Instead of registering an IEnumerable<IFoo>, you can register a CompositeFoo as IFoo:
container.Register<IFoo>(c => new CompositeFoo(
new Foo1(), new Foo2(), new Foo3()));
Now you can let the container inject that CompositeFoo in consumers that take an IFoo argument, which makes them unaware that they are in fact dealing with a list of IFoo elements.
UPDATE:
Using this composite pattern, you can easily control the lifetime of each IFoo item. It's just a matter of calling back into the container. With Funq,it would look like this:
container.Register<IFoo>(c => new CompositeFoo(
c.Resolve<Foo1>(),
c.Resolve<Foo2>(),
c.Resolve<Foo3>()));
This way you can register Foo1 as singleton and Foo2 as transient for instance. When the CompositeFoo is reused however, Foo2 will not really be transient, but it's just a matter of changing the CompositeFoo and its registration to solve this problem. For instance, you can change your CompositeFoo to the following:
public class FooComposite : IFoo
{
private readonly Func<IFoo>[] fooFactories;
public FooComposite(params Func<IFoo>[] fooFactories)
{
this.fooFactories = fooFactories;
}
void IFoo.FooThatThing(IBar bar)
{
foreach (var fooFactory in this.fooFactories)
{
var foo = fooFactory();
foo.FooThatThing(bar);
}
}
}
Now instead of injecting some IFoos into the constructor, we can inject some lambdas in it:
container.Register<IFoo>(c => new CompositeFoo(
() => c.Resolve<Foo1>(),
() => c.Resolve<Foo2>(),
() => c.Resolve<Foo3>()));
This will ensure that every time CompositeFoo's FooThatThing is called, the container is queried for new IFoo instances. This allows FooThatThing to be called multiple times by the same consumer, and even allows CompositeFoo to be registered as singleton.
This advice holds for all containers and Dependency Injection in general, and is not specific to the use of Funq.
For those of you who want the anti-pattern, simply because you might not want to implement a factory pattern, here is my version based on last 3.9.71.
Only downside is that it adds a bit more memory and you have to register the services through registerOneOfMany(). you might want to change the bag for a list with a lock (for faster reads) and switch to servicstack funq's default: ReuseScope.Default
public static class FunqExtensions
{
private static readonly ConcurrentDictionary<Type,ConcurrentBag<string>> registrations = new ConcurrentDictionary<Type, ConcurrentBag<string>>();
public static void RegisterOneOfMany<TBase, TImplementation>(this Container container, string name = null, ReuseScope scope = ReuseScope.None) where TImplementation : TBase
{
if (name == null)
name = Guid.NewGuid().ToString();
var funq = Container.GenerateAutoWireFn<TImplementation>();
container.Register<TBase>(name, (c) => funq(c))
.ReusedWithin(scope);
registrations.GetOrAdd(typeof(TBase), type => new ConcurrentBag<string>()).Add(name);
}
public static IEnumerable<T> ResolveAll<T>(this Container container)
{
ConcurrentBag<string> result;
if (registrations.TryGetValue(typeof(T), out result))
{
var rator = result.GetEnumerator();
while (rator.MoveNext())
{
yield return container.ResolveNamed<T>(rator.Current);
}
}
}
}

How to deal with scope-natured services like transactions in a DI and IOC environment

Suppose that your code is properly designed for DI and IOC through constructor injection of any dependencies. Then whether an IOC container or DI-by-hand is used or not at the composition root doesn't matter much for this problem. I think.
Anyway, I find myself over and over again in a mental struggle with how I should best deal with scope-based services, like transactions or other obviously transient operations. There are constraints that I want to abide to:
Don't let dependency interfaces be IDisposable - it's a leaky abstraction that only the actual implementing type (and the fiddler sitting at the composition root) should care about.
Don't use static service locator types deep down the graph to resolve a dependency - only inject and resolve through the constructor.
Don't pass the IOC container, if any, as a dependency down the graph.
To be able to use using, we need IDisposable, but since a dependency interface shouldn't be IDisposable, how do you get around it to get scoped behavior?
In cases like this I would inject a service factory that creates those scoped services and let the service interface derive from IDisposable. This way the factory would be responsible to create the appropriate service instances and the only point that decides which service implementation to return. You would not need to inject the scoped service anywhere.
public interface ITransaction : IDisposable
{
}
public interface ITransactionFactory
{
ITransaction CreateTransaction();
}
public class Foo
{
private readonly ITransactionFactory transactionFactory;
public Foo(ITransactionFactory transactionFactory)
{
this.transactionFactory = transactionFactory;
}
public void DoSomethingWithinTransaction()
{
using(ITransaction transaction = this.transactionFactory.CreateTransaction())
{
DoSomething();
}
}
}
Most IoC containers today have substantial built-in support for units of work of this nature.
In Autofac, the mechanism that best fits your requirements is the Owned<T> relationship type. You can see it in action (and get some more material) via this article.
Hope this helps,
Nick
Roll your own "garbage collector" maybe? Something that periodically checks IsComplete and/or an LastAccessed attribute of a Dictionary<Transaction> and wastes the "old" ones. It's "a walking memory leak" but either you clean-up explicitly (like through IDisposable) or you workout how to clean-up automatically.
There may be an AOP solution to kicking-off the "gc"... a commit/rollback sounds like a good place to cut... and maybe you won't even need a GC at all... just cleanup the transaction on the way back-up the callstack from commit or rollback.
Good luck with it. I'll be interested to see what solutions (and ideas) other people come-up with.
Cheers. Keith.
I guess another alternative you could use is to wrap your instances with a disposable type, that way it could automatically handle the disposal of the type regardless of whether the type is actually disposable. E.g, I could define something like:
public class DisposableWrapper<T> : IDisposable
{
private readonly T _instance;
private readonly IDisposable _disposable;
public DisposableWrapper(T instance)
{
_instance = instance;
_disposable = instance as IDisposable;
}
public void Dispose()
{
if (_disposable != null)
_disposable.Dispose();
}
public static implicit operator T(DisposableWrapper<T> disposableWrapper)
{
return disposableWrapper._instance;
}
}
(Hopefully with a bit more error handling!)
Given that I know at the point of disposal whether the type is disposable, I can call it accordingly. I can also provide an implicit operator to cast back to the inner type from it. With the above, and a nifty extension method:
public static class DisposableExtensions
{
public static DisposableWrapper<T> Wrap<T>(this T instance)
{
return new DisposableWrapper<T>(instance);
}
}
Let's imagine that I have a service I am injecting into a type, it could be:
public interface IUserService
{
IUser GetUser();
}
I could potentially do something like:
public HomeController(IUserService service)
{
using (var disposable = service.Wrap())
{
var user = service.GetUser();
// I can even grab it again, implicitly.
IUserService service2 = disposable;
}
}
Now regardless of whether that concrete implementation of IUserService is disposable or not, I can still safely work on the assumption that it doesn't matter.
Another quick console example:
class Program
{
static void Main(string[] args)
{
using (var instance = new ClassA().Wrap())
{
ClassA instanceA = instance;
}
using (var instance = new ClassB().Wrap())
{
ClassB instanceB = instance;
}
Console.ReadKey();
}
}
public class ClassA
{
}
public class ClassB : IDisposable
{
public void Dispose()
{
Console.Write("Disposed");
}
}

NUnit Mocking not working for Singleton Method

Bear with me, I'm new to NUnit. I come from the land of Rails, so some of this is new to me.
I have a line of code that looks like this:
var code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
I'm trying to mock it, like this (assume code is already initialized):
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
When I debug the test, getCodeByCodeNameAndType is returning null, instead of the expected code. What am I doing wrong?
NUnit version: 2.2.8
I'm sorry, but I've never used NUnit.Mocks - but I do have some experience with NMock and Moq [which, by the way, I highly recommend]. Typically, you use a mocking library to generate proxies for Interface definitions, and I presume NUnit.Mocks operates the same way.
Therefore, if you would like to mock your singleton, you will likely have to do the following,
a. Create an interface, say
// All methods you would like to mock from this class, should
// be members of this interface
public interface IWebSiteConfiguration
{
// Should match signature of method you are mocking
CodeType getCodeByCodeNameAndType (
string codeString,
CatalogType catalogType);
}
b. "Implement" interface
// You've already written the method, interface matches signature,
// should be as easy as slapping interface on class declaration
public class WebSiteConfiguration : IWebSiteConfiguration { }
c. Consume interface
alright, so step c. is where most of your work will be. Logically, if you are mocking your singleton, you are actually unit testing the consumer [which you have left out of your sample]. For c. simply add a parameter to the consumer's ctor, or add a publicly accessible property of Type 'IWebSiteConfiguration', and then internally, reference the instance member and invoke your methods against this new interface. Consider this,
was
public class MyClass
{
public MyClass () { }
public void DoSomething ()
{
// bad singleton! bad boy! static references are bad! you
// can't change them! convenient but bad!
code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType (
"some.string",
someCatalog)
}
}
becomes
public class MyClass
{
private readonly IWebSiteConfiguration _config = null;
// just so you don't break any other code, you can default
// to your static singleton on a default ctor
public MyClass () : this (WebSiteConfiguration.Instance) { }
// new constructor permits you to swap in any implementation
// including your mock!
public MyClass (IWebSiteConfiguration config)
{
_config = config;
}
public void DoSomething ()
{
// huzzah!
code = _config.getCodeByCodeNameAndType ("some.string", someCatalog)
}
}
In your unit test, create the mock, pass a reference of the mock to the consumer, and test the consumer.
[Test]
public void Test ()
{
IWebSiteConfiguration mockConfig = null;
// setup mock instance and expectation via
// NUnit.Mocks, NMock, or Moq
MyClass myClass = new MyClass (mockConfig);
myClass.DoSomething ();
// verify results
}
This also serves as a practical introduction to Dependency Injection [DI]. It's simply the practice of passing, or "injecting", references of services [eg your web site configuration class] to the consumer, rather than having the consumer invoke the service directly [eg via static singleton class].
Hope this helps :)
A DynamicMock creates a new object in-memory that represents the interface, or marshallable (inherits from MarshalByRef) class you want to mock.
Try this:
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
WebSiteConfiguration conf = (WebSiteConfiguration)_websiteConfigurationMock.MockInstance;
var x = conf.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
Note that the third line there will not work unless WebSiteConfiguration inherits from MarshalByRef.
What you typically do is mock an interface and get a new object that implements this interface, but behaves the way you've configured it to do, without having to go and make a concrete type for it, so I'm not entirely sure what you're doing is going to work unless you employ a better isolation framework, like TypeMock that can intercept calls to static methods/properties in existing objects.
Seems there is a kind of solution for this using reflection, or maybe I totally misunderstood this.
It is discussed here:
http://www.geekbeing.com/2010/05/23/how-to-unit-test-singleton-hack-in-c
Could it really works?
public class TestableSingleton : SingletonClass
{
public TestableSingleton ()
{
FieldInfo fieldInfo = typeof(SingletonClass)
.GetField("_instance",
BindingFlags.Static | BindingFlags.NonPublic);
fieldInfo.SetValue(Instance, this);
}
}
Project availabe on https://github.com/rbabreu/TestableSingleton
Actually I could not compile it on Visual Studio since the SingletonClass would have a private constructor. If someone get it to work would be great to avoid the overhead of adapter pattern.

Categories