Require Factory class in Extension Method - c#

I am working on a large legacy C# application and a task assigned to me is to remove all usages of a static factory class ServiceLocator.GetObject<T>() and replace with constructor injected dependencies throughout.
For the most part, this is simple, however there are around 50 cases in the application codebase where this is a bit tricky. For instance, Servicelocator is used in a static class, or extension method, or even a WPF MarkupExtension!.
For instance, if you were faced with a code snippet like this, what would you do? (apart from cry)
public static class MyExtensions
{
private static ISingletonServiceOne _ServiceOne = null;
private static ISingletonServiceTwo _ServiceTwo = null; // etc ...
public static SummaryHeader GetBannerSummary(this IModel rfq, object requester)
{
Guard.ArgumentNotNull(rfq, "rfq");
Guard.ArgumentNotNull(requester, "requester");
if (_ServiceOne == null)
{
_ServiceOne = ServiceLocator.GetService<ISingletonServiceOne>(requester);
Guard.ArgumentNotNull(_ServiceOne, "_ServiceOne");
}
return _ServiceOne.GetBannerSummary(rfq);
}
In the above the ServiceLocator.GetObject() method has been used in an Extension Method on IModel to locate a singleton registered service and execute a method on that using IModel.
The question is:
Are there any patterns/practices to avoid this sort of thing - a DI container needed in a static class, value-converter or extension method
Are there any patterns/practices to deal with cyclic dependencies in DI?
What would you do in the above given there is a trade off between good code and time to delivery?
I am thinking to move the GetBannerSummary() method out of extensions and only IModel in this case, however (don't laugh) there are also cases of the same ServiceLocator being used in ValueConverters (WPF) and MarkupExtensions :0
Your comments/suggestions appreciated

The only time I would ever use ServiceLocator is in static methods, e.g. extension methods, and IValueConverters as, unfortunately, there really isn't any other good way of getting dependencies.
The only (slightly) better solution is to move the ServiceLocator call out to a lazy loaded property, so that the dependency can be injected during unit testing.
In your case, however, that won't fly as you have a requester property being passed to the GetService, in which case you ideally need to add an IServiceOneFactory dependency to which you can pass your requester object. So:
public interface IServiceOneFactory
{
ISingletonServiceOne Create(object requester);
}
public static class MyExtensions
{
public static IServiceOneFactory ServiceOneFactory
{
get
{
if( _ServiceOneFactory==null)
_ServiceOneFactory = ServiceLocator.GetService<IServiceOneFactory>();
return _ServiceOneFactory;
}
set { _ServiceOneFactory = value; }
}
private static IServiceOneFactory _ServiceOneFactory = null;
private static ISingletonServiceOne _ServiceOne = null;
private static ISingletonServiceTwo _ServiceTwo = null; // etc ...
public static SummaryHeader GetBannerSummary(this IModel rfq, object requester)
{
Guard.ArgumentNotNull(rfq, "rfq");
Guard.ArgumentNotNull(requester, "requester");
if (_ServiceOne == null)
{
_ServiceOne = ServiceOneFactory.Create(requester);
Guard.ArgumentNotNull(_ServiceOne, "_ServiceOne");
}
return _ServiceOne.GetBannerSummary(rfq);
}
}

Is it an option to inject IServiceX into your classes instead of using the a static accessor class? Perhaps make GetBannerSummary method part of an abstract base class that implements IModel?
DI does not fly when you don't control object instantiation. Triggers, Behaviors or Markup-Extensions in WPF fall into that category. There is no option to using a ServiceLocator there.

Related

How to pass parameter to a class whose dependencies are wired through IoC container?

I have a class that works with a network via multiple resources. Its constructor receives arguments that are resolved at runtime by IoC container (StructureMap):
public NetworkWorker(IRetryService retryService, ILog log)
{ ... }
What I need is to control the number of resources this class uses on a use-case level - for example, client A need NetworkWorker instance that allows only one operation at a time, while client B need 10 ops at a time.
Currently this number is hardcoded in the constructor. The only way I see is to add a method void Configure(int resourceCount) that each client of NetworkWorker would call with a different value. Or may be there's a better way I don't see?
This class can do different things, but number of resources is required for every method call (Get/Send/etc methods).
P.S. is this a known technique (with a Configure method)? If it is, what's the name for it? smth like 'two-step initialization'?
I'll presume this NetworkWorker has multiple methods (otherwise you could just add a parameter to that single method).
You could use a factory pattern:
public interface INetworkWorkerFactory
{
NetworkWorker Create(int numberOfResources);
}
public class NetworkWorkerFactory : INetworkWorkerFactory
{
private readonly IContainer _container;
public NetworkWorkerFactory(IContainer container)
{
_container = container;
}
public NewtorkWorker Create(int numberOfResources)
{
var retryService = _container.GetInstance<IRetryService>();
var log = _container.GetInstance<ILog>();
return new NewtorkWorker(retryService, log, numberOfResources);
}
}
(or simply inject the required dependencies instead of the container)
and then simply
private readonly INetworkWorkerFactory _networkWorkerFactory;
public C(INetworkWorkerFactory networkWorkerFactory)
{
_networkWorkerFactory = networkWorkerFactory;
}
public void M()
{
var networkWorker = _networkWorkerFactory.Create(10);
}
Autofac uses delegate factories for this.
Other containers have equivalent mechanisms of providing auto-generated Abstract Factories - #ploeh has an awesome SO post aggregating examples.
The code in your question would look like so:
public delegate NetworkWorker Factory(IRetryService retryService);
public NetworkWorker(IRetryService retryService, ILog log)
{ ... }
A consumer would look like so (stolen from Alex's answer)
readonly NetworkWorker.Factory _networkWorkerFactory;
public C(NetworkWorker.Factory networkWorkerFactory)
{
_networkWorkerFactory = networkWorkerFactory;
}
public void M()
{
var networkWorker = _networkWorkerFactory(10);
...
}
The key difference is that you do not declare either an interface or an impl for the Abstract Factory - the delegate is the interface and Autofac 'just knows' to make the rest happen.
Another benefit of this approach (other than the code reduction) is that there's a natural path to transitioning the code to Pure DI)

How to decorate class that relies on a runtime value for creation

I'm brand new to using Simple Injector although I have been using Ninject for a long time, so I am comfortable with DI in general. One thing that attracted me to want to use Simple Injector was the ease of use of Decorators.
I have been able to successfully use decorators with Simple Injector in all normal cases where the dependencies are resolved when the service is requested. However, I am having a hard time figuring out if there is a way to get my decorators applied in a case when the service must be constructed using a runtime value.
In Ninject, I could pass a ConstructorArgument to the kernel.Get<IService> request that could be inherited down the chain of N decorators all the way to the "real" implementing class. I cannot figure out a way to replicate that using Simple Injector.
I have put some very basic code below to illustrate. What I would want to do in the real world would be to pass an IMyClassFactory instance into other classes in my application. Those other classes could then use it to create IMyClass instances using the IRuntimeValue they would provide. The IMyClass instance they got from the IMyClassFactory would be decorated automatically by the registered decorators.
I know I could manually apply my decorator(s) in my IMyClassFactory or any Func<IMyClass> I could come up with, but I would like it to "just work".
I keep going around and around trying to abstract out the MyClass construction, but I can't figure out how to get it to resolve with the IRuntimeValue constructor argument and be decorated.
Am I overlooking an obvious solution?
using System;
using SimpleInjector;
using SimpleInjector.Extensions;
public class MyApp
{
[STAThread]
public static void Main()
{
var container = new Container();
container.Register<IMyClassFactory, MyClassFactory>();
container.RegisterDecorator(typeof (IMyClass), typeof (MyClassDecorator));
container.Register<Func<IRuntimeValue, IMyClass>>(
() => r => container.GetInstance<IMyClassFactory>().Create(r));
container.Register<IMyClass>(() => ?????)); // Don't know what to do
container.GetInstance<IMyClass>(); // Expect to get decorated class
}
}
public interface IRuntimeValue
{
}
public interface IMyClass
{
IRuntimeValue RuntimeValue { get; }
}
public interface IMyClassFactory
{
IMyClass Create(IRuntimeValue runtimeValue);
}
public class MyClassFactory : IMyClassFactory
{
public IMyClass Create(IRuntimeValue runtimeValue)
{
return new MyClass(runtimeValue);
}
}
public class MyClass : IMyClass
{
private readonly IRuntimeValue _runtimeValue;
public MyClass(IRuntimeValue runtimeValue)
{
_runtimeValue = runtimeValue;
}
public IRuntimeValue RuntimeValue
{
get
{
return _runtimeValue;
}
}
}
public class MyClassDecorator : IMyClass
{
private readonly IMyClass _inner;
public MyClassDecorator(IMyClass inner)
{
_inner = inner;
}
public IRuntimeValue RuntimeValue
{
get
{
return _inner.RuntimeValue;
}
}
}
Edit 1:
Ok, thanks to Steven for the great answer. It has given me a couple of ideas.
Maybe to make it a little more concrete though (although not my situation, more "classic"). Say I have an ICustomer that I create at runtime by reading a DB or deserializing from disk or something. So I guess that would be considered a "newable" to quote one of the articles Steven linked. I would like to create an instance of ICustomerViewModel so I can display and manipulate my ICustomer. My concrete CustomerViewModel class takes in an ICustomer in its constructor along with another dependency that can be resolved by the container.
So I have an ICustomerViewModelFactory that has a .Create(ICustomer customer) method defined which returns ICustomerViewModel. I could always get this working before I asked this question because in my implementation of ICustomerViewModelFactory I could do this (factory implemented in composition root):
return new CustomerViewModel(customer, container.GetInstance<IDependency>());
My issue was that I wanted my ICustomerViewModel to be decorated by the container and newing it up bypassed that. Now I know how to get around this limitation.
So I guess my follow-up question is: Is my design wrong in the first place? I really feel like the ICustomer should be passed into the constructor of CustomerViewModel because that demonstrates intent that it is required, gets validated, etc. I don't want to add it after the fact.
Simple Injector explicitly lacks support for passing on runtime values through the GetInstance method. Reason for this is that runtime values should not be used when the object graph is constructed. In other words, the constructors of your injectables should not depend on runtime values. There are several problems with doing that. First of all, your injectables might need to live much longer than those runtime values do. But perhaps more importantly, you want to be able to verify and diagnose your container's configuration and that becomes much more troublesome when you start using runtime values in the object graphs.
So in general there are two solutions for this. Either you pass on the runtime value through the method call graph or you create a 'contextual' service that can supply this runtime value when requested.
Passing on the runtime value through the call graph is especially a valid solution when you practice architectures like this and this where you pass on messages through your system or when the runtime value can be an obvious part of the service's contract. In that case it is easy to pass on the runtime value with the message or the method and this runtime value will also pass through any decorator on the way through.
In your case this would mean that the factory creates the IMyService without passing in the IRuntimeValue and your code passes this value on to the IMyService using the method(s) it specifies:
var service = _myServiceFactory.Create();
service.DoYourThing(runtimeValue);
Passing through the runtime value through the call graph however is not always a good solution. Especially when this runtime value should not be part of the contract of the message that is sent. This especially holds for contextual information use as information about the current logged in user, the current system time, etc. You don't want to pass this information through; you just want it to be available. We don't want this, because this would give an extra burden to the consumers of passing the right value every time, while they probably shouldn't even be able to change this information (take the user in who's context the request is executed for instance).
In that case you should define service that can be injected and allows retrieving this context. For instance:
public interface IUserContext {
User CurrentUser { get; }
}
public interface ITimeProvider {
DateTime Now { get; }
}
In these cases the current user and the current time aren't injected directly into a constructor, but instead these services are. The component that needs to access the current user can simply call _userContext.CurrentUser and this will be done after the object is constructed (read: not inside the constructor). Thus: in a lazy fashion.
This does mean however that the IRuntimeValue must be set somewhere before MyClass gets invoked. This probably means you need to set it inside the factory. Here's an example:
var container = new Container();
var context = new RuntimeValueContext();
container.RegisterSingle<RuntimeValueContext>(context);
container.Register<IMyClassFactory, MyClassFactory>();
container.RegisterDecorator(typeof(IMyClass), typeof(MyClassDecorator));
container.Register<IMyClass, MyClass>();
public class RuntimeValueContext {
private ThreadLocal<IRuntimeValue> _runtime;
public IRuntimeValue RuntimeValue {
get { return _runtime.Value; }
set { _runtime.Value = value; }
}
}
public class MyClassFactory : IMyClassFactory {
private readonly Container _container;
private readonly RuntimeValueContext context;
public MyClassFactory(Container container, RuntimeValueContext context) {
_container = container;
_context = context;
}
public IMyClass Create(IRuntimeValue runtimeValue) {
var instance = _container.GetInstance<IMyClass>();
_context.RuntimeValue = runtimeValue;
return instance;
}
}
public class MyClass : IMyClass {
private readonly RuntimeValueContext _context;
public MyClass(RuntimeValueContext context) {
_context = context;
}
public IRuntimeValue RuntimeValue { get { return _context.Value; } }
}
You can also let the MyClass accept the IRuntimeValue and make the following registration:
container.Register<IRuntimeValue>(() => context.Value);
But the disallows verifying the object graph, since Simple Injector will ensure that registrations never return null, but context.Value will be null by default. So another option is to do the following:
container.Register<IMyClass>(() => new MyClass(context.Value));
This allows the IMyClass registration to be verified, but will during verification still create a new MyClass instance that is injected with a null value. If you have a guard clause in the MyClass constructor, this will fail. This registration however disallows MyClass to be auto-wired by the container. Auto-wiring that class can come in handy when you've got more dependencies to inject into MyClass for instance.

Ways to setup a Ninject singleton

I have a class (MyFacade) that I injected parameter(s) with Ninject:
class MyFacade
{
IDemoInterface demo;
public MyFacade(IDemoInterface demo)
{
this.demo = demo;
}
public void MyMethod()
{
Console.WriteLine(demo.GetInfo());
}
}
Of course, I have to setup the Ninject to inject the appropiate implementation of my parameter (IDemoInterface)
I know, I can instantiate MyFacade object by doing kernel.Get<MyFacade>(); without setting anything else. Currently my facade doesn't have an interface (because it is my only implementation, maybe I will add its interface for standard proposes)
if I want to make this facade singlenton, I know two ways: create a empty constructor and pass a parameter by doing this kernel.Get<IDemoInterface>(); or by setup Ninject like: kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
The second one look a better approach, but do you know any other way to setup it in a singleton way?
When setting up your bindings, you need to bind your dependencies. It is always better to setup your dependencies in your bindings, as opposed to doing a kernel.Get<T>() in a constructor. You are using IOC, so leverage the framework you are using to do the injection for you.
In your second example binding, what you are missing is binding in your IDemoInterface. Your bindings should look like this:
//bind the dependency to the implementation.
kernel.Bind<IDemoInterface>().To<DemoInterface>();
//since you bound your dependency, ninject should now have
// all the dependencies required to instantiate your `MyFacade` object.
kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
If you do not want the container to manage the lifecycle of your singleton by using InSingletonScope(), but still wants it to get injected, I can think of 2 ways to go about it. Choose which one suits better to your needs. Consider the following ISingleton (name your interface) implementation:
public class ConcreteSingleton : ISingleton
{
private static readonly Lazy<ConcreteSingleton> _instance = new Lazy<ConcreteSingleton>(() => new ConcreteSingleton());
private ConcreteSingleton() { }
public static ConcreteSingleton Instance
{
get
{
return _instance.Value;
}
}
}
Alter the singleton class to have a GetInstance(...) method
In this method (my preferred approach), you won't be calling kernel.Inject(instance) each time, only for the first time the singleton is initialized. Adding the following method to your ConcreteSingleton class:
public static ConcreteSingleton GetInstance(IKernel kernelForInjection)
{
if (_instance.IsValueCreated == false)
{
kernelForInjection.Inject(_instance.Value);
}
return _instance.Value;
}
And using this binding:
kernel.Bind<ISingleton>().ToMethod(c => ConcreteSingleton.GetInstance(c.Kernel));
Will achieve the desired behavior of not having a public constructor but enabling your facade to be efficiently injected.
Perform injection each time the ISingleton instance is requested
If by any reason you are not allowed to modify your ConcreteSingleton: This approach will wrap the singleton creation in a provider to efficiently inject the instance only for the first time it is created. It is important to note that the provider itself must be registered as a singleton.
internal class ConcreteSingletonProvider : Provider<ISingleton>
{
public IKernel Kernel { get; set; }
//Just a wrapper
private readonly Lazy<ISingleton> _lazy = new Lazy<ISingleton>(() => ConcreteSingleton.Instance);
public ConcreteSingletonProvider(IKernel kernel)
{
Kernel = kernel;
}
protected override ISingleton CreateInstance(IContext context)
{
if (_lazy.IsValueCreated == false)
{
Kernel.Inject(ConcreteSingleton.Instance);
}
return _lazy.Value;
}
}
And your bindings should be like this:
kernel.Bind<ISingleton>().ToProvider<ConcreteSingletonProvider>();
kernel.Bind<ConcreteSingletonProvider>().ToSelf().InSingletonScope();
This gist has a complete working sample for the above approach.
Hope that helps!

How to Mock a Static Singleton?

I have number of classes I've been asked to add some unit tests to with Rhino Mocks and having some issues.
First off, I know RhinoMocks doesn't allow for the mocking of Static members. I'm looking for what options I have (besides using TypeMock).
An example of the class I have is similar to the below:
class Example1 : ISomeInterface
{
private static ISomeInterface _instance;
private Example1()
{
// set properties via private static methods
}
static Example1()
{
_instance = new Example1();
}
public static ISomeInterface Instance()
{
get { return _instance; }
}
// Instance properties
// Other Instance Properties that represent objects that follow a similar pattern.
}
So when I call the above class, it looks something like this...
Example1.Instance.SomeObject.GoDownARabbitHole();
Is there a way for me to mock out the SomeObject.GoDownARabbitHole() in this situation or mock out the Instance?
Discouraged by threads like this, it took me quite some time to notice, that singletons are not that hard to mock. After all why are we using c#?
Just use Reflection.
With provided sample code you need to make sure the static constructor is called before setting the static field to the mocked object. Otherwise it might overwrite your mocked object. Just call anything on the singleton that has no effect before setting up the test.
ISomeInterface unused = Singleton.Instance();
System.Reflection.FieldInfo instance = typeof(Example1).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
Mock<ISomeInterface> mockSingleton = new Mock<ISomeInterface>();
instance.SetValue(null, mockSingleton.Object);
I provided code for mocking with Moq, but I guess Rhino Mocks is quite similar.
Singletons are at odds with Testability because they are so hard to change. You would be much better off using Dependency Injection to inject an ISomeInterface instance into your consuming classes:
public class MyClass
{
private readonly ISomeInterface dependency;
public MyClass(ISomeInterface dependency)
{
if(dependency == null)
{
throw new ArgumentNullException("dependency");
}
this.dependency = dependency;
}
// use this.dependency in other members
}
Notice how the Guard Claus together with the readonly keyword guarantees that the ISomeInterface instance will always be available.
This will allow you to use Rhino Mocks or another dynamic mock library to inject Test Doubles of ISomeInterface into the consuming classes.
Here's a low-touch approach that uses a delegate, which can be set initially and changed at runtime. It's better explained by example (specifically, mocking DateTime.Now):
http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/11/09/systemtime-versus-isystemclock-dependencies-revisited.aspx
Example from Book: Working Effectively with Legacy Code
To run code containing singletons in a test harness, we have to relax the singleton property. Here’s how we do it. The first step is to add a new static method to the singleton class. The method allows us to replace the static instance in the singleton. We’ll call it
setTestingInstance.
public class PermitRepository
{
private static PermitRepository instance = null;
private PermitRepository() {}
public static void setTestingInstance(PermitRepository newInstance)
{
instance = newInstance;
}
public static PermitRepository getInstance()
{
if (instance == null)
{
instance = new PermitRepository();
}
return instance;
}
public Permit findAssociatedPermit(PermitNotice notice)
{
...
}
...
}
Now that we have that setter, we can create a testing instance of a
PermitRepository and set it. We’d like to write code like this in our test setup:
public void setUp() {
PermitRepository repository = new PermitRepository();
...
// add permits to the repository here
...
PermitRepository.setTestingInstance(repository);
}
Check out Dependency Injection.
You've already began this, but for hard to test classes (statics etc...) you can use the adapter design pattern to write a wrapper around this hard to test code. Using the interface of this adapter, you can then test your code in isolation.
For any unit testing advice, and further testing issues check out the Google Testing Blog, specifically Misko's articles.
Instance
You say you are writing tests, so it may be too late, but could you refactor the static to the instance? Or is there a genuine reason why said class should remain a static?
You can mock the interface, ISomeInterface. Then, refactor the code that uses it to use dependency injection to get the reference to the singleton object. I have come across this problem many times in our code and I like this solution the best.
for example:
public class UseTheSingleton
{
private ISomeInterface myX;
public UseTheSingleton(ISomeInterface x)
{
myX = x;
}
public void SomeMethod()
{
myX.
}
}
Then ...
UseTheSingleton useIt = UseTheSingleton(Example1.Instance);
You don't have to fix all the uses at once, just the one you're dealing with now. Add an ISomeInterface field to the class under test and set it through the constructor. If you're using Resharper (you are using Resharper, aren't you?), most of this will be trivial to do. If this is really fiddly, you can have more than one constructor, one which sets the new dependency field, the other which calls the first one with the singleton as a default value.

C# - Type Parameters in Constructor - No Generics

I have a class that I am trying to do unit tests on. The class is a WCF Service Class. (Making it a generics class is not my goal.)
I have a data access layer (DAL) type (called UserDAL) that is instantiated in many methods. To get these methods under test, I need to get this local variables mocked. (Each instance of UserDAL has method specific value in it, so changing it a class level variable would result in messy code, so I would rather not do that.)
What I am thinking would be nice is to overload the constructor and pass in a type to use in the local methods. The empty param constructor would still create a normal UserDAL, but the overloaded one would have a mock type that implements IUserDAL.
I am not sure of the syntax to say I want to pass in a type. Note that I am not trying to pass in a variable, but a type.
Example:
public class MyWCFClass: IMyWCFClass
{
private TypeParam _myUserDALType;
public MyWCFClass()
{
_myUserDALType = UserDAL;
}
public MyWCFClass(TypeParam myUserDALType)
{
_myUserDALType = myUserDALType;
}
//methods to use it
public MyMethod()
{
IUserDAL userDAL = new _myUserDALType();
//Call method in IUserDAL
userDAL.CreateUser();
}
// Several similar methods that all need a different UserDAL go here
.....
}
So, I don't know what kind of type TypeParam is (I made that up) or if this kind of think is even possible.
If you have a non generics solution that would be great.
What you are really looking for is Dependency Injection, but you can do this by passing in a Type argument and then using Activator.CreateInstance(Type) to create the object when you need it.
As far as doing real DI (which will make doing this testing a lot easier), I know that Spring.Net works reasonable well.
You mean Type, using Activator.CreateInstance to create instances:
public class MyWCFClass: IMyWCFClass
{
private Type _myUserDALType;
public MyWCFClass()
{
_myUserDALType = typeof(UserDAL);
}
public MyWCFClass(Type myUserDALType)
{
_myUserDALType = myUserDALType;
}
//methods to use it
public void MyMethod()
{
IUserDAL userDAL = (IUserDAL) Activator.CreateInstance(_myUserDALType );
//Call method in IUserDAL
userDAL.CreateUser();
}
}
Use a Type, and use Activator.CreateInstance to instantiate it:
private Type _myUserDALType;
IUserDAL userDAL = Activator.CreateInstance(_myUserDALType) as IUserDAL;
Your real problem is not in the generics or lack thereof. Your real problem is that MyWFCClass is calling both new and the method. As per Misko Hevery, you get the best testability by separating classes that call new from classes that implement logic. Instead of having MyWFCClass somehow know the type that you want to implement and using reflection, just pass the IUserDal object to the constructor, allowing the test harness to pass in a mock object when needed.
If, for some reason, you can't do this and you can't use generics, then you have to do it yourself. Pass a Type object to the MyWFCClass constructor, then use reflection to find and invoke the constructor you want.
If you want to pass in a type, you can use the Type object:
public class A
{
public A(Type classType)
{
object myObject = Activator.CreateInstance(...classType...);
}
}
public class B
{
...
}
public class C
{
public static void main(string[] args)
{
A a = new A(typeof(B));
}
}
Far simpler, and more consistent with other applications that have this problem, would be to extract an interface on UserDal, then you would have something more like:
public MyWCFClass() : this(new UserDAL())
{
}
public MyWCFClass(IUserDal userDAL)
{
_myUserDAL = myUserDAL;
}
This is also easier to use with dependency-injection frameworks than your proposed method, though that's certainly a secondary concern
(Edited to clarify an alternative solution based on other comments)
If your DAL is essentially worthless after use because it is mutated, take a constructor with IUserDalFactory instead, with one method Create().
If IUserDAL defines the interface that your WCF service needs to get its job done, why not just take an instance of it as a constructor parameter? And since WCF requires a default constructor, why not have that default constructor call your parameterized constructor with a default implementation?
public class MyWCFClass : IMyWCFClass
{
private readonly IUserDAL _userDAL;
public MyWCFClass()
: this(new DefaultUserDAL())
{
}
public MyWCFClass(IUserDAL userDAL)
{
_userDAL = userDAL;
}
}
If you're using a dependency injection container, you could expose it as a singleton and satisfy the parameterized constructor by using that singleton:
public MyWCFClass()
this(Container.Instance.Resolve<IUserDAL>())
{
}
With this approach, your WCF class has everything it needs to get its job done, but it is still unit-testable. Moreover, it is not responsible for creating its dependencies, which is a good thing.
In C# there is a type called "Type". With it you can create a parameter and pass in any valid type.
private void MyMethod(Type myType)
{
//Do something
}

Categories

Resources