I am applying the Service Locator pattern as described in Game Programming Patterns, and am wondering about a possible generic implementation. The following code does work, but I am confused about using a class that is both generic and static.
The idea of the following C# code is to provide a "global" service to other parts of the application, exposing only an interface rather than the full implementation. Each service registered using this method will only have one instance in the application, but I want to be able to easily swap in/out different implementations of the provided interfaces.
My question is: when I use the following class to provide different services throughout my application, how does C# know that I am referring to different services of different types? Intuitively, I would almost think that the static variable, _service, would be overridden with each new service.
public static class ServiceLocator<T>
{
static T _service;
public static T GetService()
{
return _service;
}
public static void Provide(T service)
{
_service = service;
}
}
Here's some usage:
// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocator<ICamera>.Provide(_camera);
// Elsewhere, usage:
ICamera camera = ServiceLocator<ICamera>.GetService();
// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocator<IMap>.Provide(CurrentMap);
// Elsewhere, using this different service:
IMap map = ServiceLocator<IMap>.GetService();
C# creates a separate closed type for every combination of generic parameters for open type.
Since every combination of generic parameters creates a separate class, calling a static constructor and creating own members for each of them.
You can think of them like of different classes.
public static class GenericCounter<T>
{
public static int Count { get; set; } = 0;
}
GenericCounter<int>.Count++;
GenericCounter<int>.Count++;
GenericCounter<string>.Count++;
Console.WriteLine(GenericCounter<double>.Count); // 0
Console.WriteLine(GenericCounter<int>.Count); // 2
Console.WriteLine(GenericCounter<string>.Count); // 1
This code outputs:
0
2
1
For example, in your case, behavior will be the same as if you created two separate classes:
public static class ServiceLocatorOfIMap
{
static IMap _service;
public static IMap GetService()
{
return _service;
}
public static void Provide(IMap service)
{
_service = service;
}
}
public static class ServiceLocatorOfICamera
{
static ICamera _service;
public static ICamera GetService()
{
return _service;
}
public static void Provide(ICamera service)
{
_service = service;
}
}
and used it like this:
// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocatorForICamera.Provide(_camera);
// Elsewhere, usage:
ICamera camera = ServiceLocatorForICamera.GetService();
// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocatorForIMap.Provide(CurrentMap);
// Elsewhere, using this different service:
IMap map = ServiceLocatorForIMap.GetService();
In general, it is similar to what C# does when it meets static generic classes.
I use this for cases where I can't use dependency injection all the way down (like WebForms) but I want to write testable classes that are resolved by a DI container.
The usage looks like
using(var resolved = new ResolvedService<ISomeService>())
{
resolved.Service.DoSomething();
}
The good:
You can use a DI container to resolve and release resources
It's disposable, and disposing causes the container to release the resources
It keeps the container and service registrations out of sight
The bad:
It requires a static class, but that's also in the composition root so it's not too bad.
As written it depends directly on Windsor. It's easy to replace that with any other container. Maybe one day I'll break this apart so that ServiceLocator isn't coupled to any particular container. But for now it's trivial to change that.
Using this means that while the larger component (like an .aspx page) isn't testable, what I inject into it is testable. It just gave me a crazy thought - I could write orchestrators for WebForms pages so that they're mostly testable. But hopefully I'll never need to do that.
internal class ServiceLocator
{
private static IWindsorContainer _container;
internal static void Initialize(IWindsorContainer container)
{
_container = container;
}
internal static TService Resolve<TService>(string key = null)
{
if (_container == null)
{
throw new InvalidOperationException(
"ServiceLocator must be initialized with a container by calling Initialize(container).");
}
try
{
return string.IsNullOrEmpty(key)
? _container.Resolve<TService>()
: _container.Resolve<TService>(key);
}
catch (ComponentNotFoundException ex)
{
throw new InvalidOperationException(string.Format("No component for {0} has been registered.", typeof(TService).FullName), ex);
}
}
internal static void Release(object resolved)
{
_container.Release(resolved);
}
}
public class ResolvedService<TService> : IDisposable
{
private bool _disposed;
private readonly TService _resolvedInstance;
public TService Service
{
get { return _resolvedInstance; }
}
public ResolvedService(string key = null)
{
_resolvedInstance = ServiceLocator.Resolve<TService>(key);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~ResolvedService()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
ServiceLocator.Release(_resolvedInstance);
_disposed = true;
}
}
Related
I know this question might look like it's a duplicate but please let me explain.
So I created several components that use a pluggable architecture, basically I can freely add new implementations and they will be injected and processed automatically for me. This is really handy in several scenarios.
I'm going to talk about the simplest one, validating components.
One of the reasons to use a design like this is that I like to expose my roles explicitly as explained by Udi Dahan
Basically I have code like this:
public interface IValidatorRuner
{
void Run<TTarget>(TTarget target);
}
public class ValidatorRunenr : IValidatorRuner
{
private readonly IServiceLocator _serviceLocator;
public ValidatorRunenr(IServiceLocator serviceLocator)
{
_serviceLocator = serviceLocator;
}
public void Run<TTarget>(TTarget target)
{
// this is the dynamic/pluggable phase
// is this an antipattern???
var foundValdiators = _serviceLocator.GetAllInstances<IValidator<TTarget>>();
foreach (var valdiator in foundValdiators)
{
valdiator.IsSatisfiedBy(target);
}
}
}
This code lets me expose my validation rules explicitly like this:
//this will allow me to create validators in this way
//and they will be automatically injected and resolved for me
//(easy, to read, easy to write, easy to test, pff I could even smoke this validator easily)
public class OneValdiationRuleExplicitlyExposedAndEasyToTest : IValidator<Person>
{
public bool IsSatisfiedBy(Person target)
{
return target.Age > 18;
}
}
public class Person
{
public int Age { get; set; }
}
public interface IValidator<TTarget>
{
bool IsSatisfiedBy(TTarget target);
}
And I will use this code like this:
//usage
public class SomeCommandHandler
{
private readonly IValidatorRuner _validatorRuner;
public SomeCommandHandler(IValidatorRuner validatorRuner)
{
_validatorRuner = validatorRuner;
}
public void SomeMethod()
{
_validatorRuner.Run(new Person{Age = 16});
}
}
Validation was just one example, I also use it to fire domain events and to run pipelines and filters in the same pluggable way
Is using the service locator in this way an anti-pattern?
I know I might be hiding some dependencies, but the thing is that the dependencies are dynamically injected and discovered when the application initializes (Composition root)
Your thoughts will be greatly appreciated
In my opinion, the primary issue with your code sample is that the service locator is itself injected into the implementation of ValidatorRunner. For me, this is an anti-pattern, but perhaps not the one you're asking about.
Any answer I might give boils down to the capabilities of your service locator implementation. But for sure it should not be passed into the constructor of your class. Instead, the service locator should itself pass these things in when you ask it for an implementation of "IValidatorRuner"
As an example, you can inject a factory that knows how to load the dynamic validator instances for a given type.
If anyone is interested, I found a way to remove the ServiceLocator in my objects and still dynamically load/discover dependencies at run time.
The way I solved it was by registering my components in my DI container in the following way (using the Mediator pattern):
Binding mediator (shortbus) with/to ninject
var kernel = new StandardKernel();
kernel.Bind(x => x.FromThisAssembly()
.SelectAllClasses()
.InheritedFromAny(
new[]
{
typeof(IValidatorRunner<>)
})
.BindDefaultInterfaces());
And my final implementation looks like:
public interface IValidatorRuner<in TTarget>
{
void Run(TTarget target);
}
public class ValidatorRunenr<TTarget> : IValidatorRuner<TTarget>
{
private readonly IEnumerable<IValidator<TTarget>> _validators;
public ValidatorRunenr(IEnumerable<IValidator<TTarget>> validators)
{
_validators = validators;
}
public void Run(TTarget target)
{
foreach (var valdiator in _validators)
{
valdiator.IsSatisfiedBy(target);
}
}
}
Usage
//usage
public class SomeCommandHandler
{
private readonly IValidatorRuner<OneValdiationRuleExplicitlyExposedAndEasyToTest> _validatorRuner;
public SomeCommandHandler(IValidatorRuner<OneValdiationRuleExplicitlyExposedAndEasyToTest> validatorRuner)
{
_validatorRuner = validatorRuner;
}
public void SomeMethod()
{
_validatorRuner.Run(new Person{Age = 16});
}
}
In few words, by registering an opened generic type, my container resolves any call to that type creating a concrete-closed-generic-type instance at runtime for me.
As you can see in the usage, I do not have to create a specific concrete-closed-generic type of IValidatorRunner<OneValdiationRuleExplicitlyExposedAndEasyToTest> because the container creates one for me.
And there you go, now I'm happy because I removed the service locator from my domain objects =)
I have a class with the following structure
class Measure
{
public MeasureType measureType { get; set; }
public readonly IMeasureService _service ;
public Measure(IMeasureService service)
{
_service = service;
}
public Calculate()
{
_service.Calculate(this);
}
}
So i have different implementation of MeasureService for different measureTypes. Is it possible to use StructureMap to inject the corresponding MeasureService based on the measureType.
MeasureType is just an enum type and will never get changed throughout the instance.
StructureMap cannot be instructed to do that for a simple reason:
at the time the instance is created, the measureType property cannot be set.
you cannot set the IMeasureService dependency at a later time, because it's readonly (and should probably be private as well)
Therefore, the solutions to this problem have more to do with the design of your classes than with StructureMap.
Here are the solutions I would typically choose in such a scenario:
1) Delegate the task of choosing the right IMeasureService implementation to a different component.
The component could, for example, be called MeasureServiceFactory and have the following implementation:
public class MeasureServiceFactory
{
private readonly Func<MeasureServiceType1> _type1Service;
private readonly Func<MeasureServiceType2> _type2Service;
public MeasureServiceFactory(
Func<MeasureServiceType1> type1Service,
Func<MeasureServiceType2> type2Service)
{
_type1Service = type1Service;
_type2Service = type2Service;
}
public IMeasureService GetServiceForType(MeasureType type)
{
switch (type)
{
case MeasureType.Type1:
return _type1Service();
case MeasureType.Type2:
return _type2Service();
default:
throw new ApplicationException("Unexpected measure type!");
}
}
}
Note that StructureMap will automatically inject the two Funcs with appropriate calls to the container's GetInstance() method in order to properly resolve the required service.
Now, the Measure class will no longer have a direct IMeasureService dependency, but will depend on the factory instead:
public class Measure
{
public MeasureType measureType { get; set; }
private readonly MeasureServiceFactory _measureServiceFactory;
public Measure(MeasureServiceFactory measureServiceFactory)
{
_measureServiceFactory = measureServiceFactory;
}
public void Calculate()
{
var service = _measureServiceFactory.GetServiceForType(measureType);
service.Calculate(this);
}
}
Note that no StructureMap configuration is required. The container will be able to resolve everything correctly.
2) In order to keep the Measure class untouched, you could make the MeasureServiceFactory implement the IMeasureService interface:
public class MeasureServiceFactory : IMeasureService
{
private readonly Func<MeasureServiceType1> _type1Service;
private readonly Func<MeasureServiceType2> _type2Service;
public MeasureServiceFactory(
Func<MeasureServiceType1> type1Service,
Func<MeasureServiceType2> type2Service)
{
_type1Service = type1Service;
_type2Service = type2Service;
}
public void Calculate(Measure measure)
{
var service = GetServiceForType(measure.measureType);
service.Calculate(measure);
}
private IMeasureService GetServiceForType(MeasureType type)
{
switch (type)
{
case MeasureType.Type1:
return _type1Service();
case MeasureType.Type2:
return _type2Service();
default:
throw new ApplicationException("Unexpected measure type!");
}
}
}
Now, with your original Measure class, only this SM configuration is required to ake everything work:
x.For<IMeasureService>().Use<MeasureServiceFactory>();
3) If the logic inside the IMeasureService implementors is not very complicated, consider putting it in a single class and perform different things depending on the measureType of the Measure object (which you already have access to).
I know, this seems like a step back, but there are some cases in which I prefer to do just that: when the business logic is not overly complex and pretty unlikely to change.
I built a .NET ASMX web service connecting to an SQL Server database. There is a web service call GetAllQuestions().
var myService = new SATService();
var serviceQuestions = myService.GetAllQuestions();
I saved the result of GetAllQuestions to GetAllQuestions.xml in the local application folder
Is there any way to fake the web service call and use the local xml result?
I just want to take the contents of my entire sql table and have the array of objects with correlating property names automatically generated for me just like with LINQ to SQL web services.
Please keep in mind that I am building a standalone Monotouch iPhone application.
Use dependency injection.
//GetSATService returns the fake service during testing
var myService = GetSATService();
var serviceQuestions = myService.GetAllQuestions();
Or, preferably, in the constructor for the object set the SATService field (so the constructor requires the SATService to be set. If you do this, it will be easier to test.
Edit: Sorry, I'll elaborate here. What you have in your code above is a coupled dependency, where your code creates the object it is using. Dependency injection or the Inversion of Control(IOC) pattern, would have you uncouple that dependency. (Or simply, don't call "new" - let something else do that - something you can control outside the consumer.)
There are several ways to do this, and they are shown in the code below (comments explain):
class Program
{
static void Main(string[] args)
{
//ACTUAL usage
//Setting up the interface injection
IInjectableFactory.StaticInjectable = new ConcreteInjectable(1);
//Injecting via the constructor
EverythingsInjected injected =
new EverythingsInjected(new ConcreteInjectable(100));
//Injecting via the property
injected.PropertyInjected = new ConcreteInjectable(1000);
//using the injected items
injected.PrintInjectables();
Console.WriteLine();
//FOR TESTING (normally done in a unit testing framework)
IInjectableFactory.StaticInjectable = new TestInjectable();
EverythingsInjected testInjected =
new EverythingsInjected(new TestInjectable());
testInjected.PropertyInjected = new TestInjectable();
//this would be an assert of some kind
testInjected.PrintInjectables();
Console.Read();
}
//the inteface you want to represent the decoupled class
public interface IInjectable { void DoSomething(string myStr); }
//the "real" injectable
public class ConcreteInjectable : IInjectable
{
private int _myId;
public ConcreteInjectable(int myId) { _myId = myId; }
public void DoSomething(string myStr)
{
Console.WriteLine("Id:{0} Data:{1}", _myId, myStr);
}
}
//the place to get the IInjectable (not in consuming class)
public static class IInjectableFactory
{
public static IInjectable StaticInjectable { get; set; }
}
//the consuming class - with three types of injection used
public class EverythingsInjected
{
private IInjectable _interfaceInjected;
private IInjectable _constructorInjected;
private IInjectable _propertyInjected;
//property allows the setting of a different injectable
public IInjectable PropertyInjected
{
get { return _propertyInjected; }
set { _propertyInjected = value; }
}
//constructor requires the loosely coupled injectable
public EverythingsInjected(IInjectable constructorInjected)
{
//have to set the default with property injected
_propertyInjected = GetIInjectable();
//retain the constructor injected injectable
_constructorInjected = constructorInjected;
//using basic interface injection
_interfaceInjected = GetIInjectable();
}
//retrieves the loosely coupled injectable
private IInjectable GetIInjectable()
{
return IInjectableFactory.StaticInjectable;
}
//method that consumes the injectables
public void PrintInjectables()
{
_interfaceInjected.DoSomething("Interface Injected");
_constructorInjected.DoSomething("Constructor Injected");
_propertyInjected.DoSomething("PropertyInjected");
}
}
//the "fake" injectable
public class TestInjectable : IInjectable
{
public void DoSomething(string myStr)
{
Console.WriteLine("Id:{0} Data:{1}", -10000, myStr + " For TEST");
}
}
The above is a complete console program that you can run and play with to see how this works. I tried to keep it simple, but feel free to ask me any questions you have.
Second Edit:
From the comments, it became clear that this was an operational need, not a testing need, so in effect it was a cache. Here is some code that will work for the intended purpose. Again, the below code is a full working console program.
class Program
{
static void Main(string[] args)
{
ServiceFactory factory = new ServiceFactory(false);
//first call hits the webservice
GetServiceQuestions(factory);
//hists the cache next time
GetServiceQuestions(factory);
//can refresh on demand
factory.ResetCache = true;
GetServiceQuestions(factory);
Console.Read();
}
//where the call to the "service" happens
private static List<Question> GetServiceQuestions(ServiceFactory factory)
{
var myFirstService = factory.GetSATService();
var firstServiceQuestions = myFirstService.GetAllQuestions();
foreach (Question question in firstServiceQuestions)
{
Console.WriteLine(question.Text);
}
return firstServiceQuestions;
}
}
//this stands in place of your xml file
public static class DataStore
{
public static List<Question> Questions;
}
//a simple question
public struct Question
{
private string _text;
public string Text { get { return _text; } }
public Question(string text)
{
_text = text;
}
}
//the contract for the real and fake "service"
public interface ISATService
{
List<Question> GetAllQuestions();
}
//hits the webservice and refreshes the store
public class ServiceWrapper : ISATService
{
public List<Question> GetAllQuestions()
{
Console.WriteLine("From WebService");
//this would be your webservice call
DataStore.Questions = new List<Question>()
{
new Question("How do you do?"),
new Question("How is the weather?")
};
//always return from your local datastore
return DataStore.Questions;
}
}
//accesses the data store for the questions
public class FakeService : ISATService
{
public List<Question> GetAllQuestions()
{
Console.WriteLine("From Fake Service (cache):");
return DataStore.Questions;
}
}
//The object that decides on using the cache or not
public class ServiceFactory
{
public bool ResetCache{ get; set;}
public ServiceFactory(bool resetCache)
{
ResetCache = resetCache;
}
public ISATService GetSATService()
{
if (DataStore.Questions == null || ResetCache)
return new ServiceWrapper();
else
return new FakeService();
}
}
Hope this helps. Good luck!
when you say fake the call, are you just testing the client side?
you could use fiddler, intercept the request and return the local xml file to the client. No messing around with your client code then.
To elaborate on Audie's answer
Using DI would get you what you want. Very simply you would create an interface that your real object and your mock object both implement
public interface IFoo
{}
Then you would have your GetSATService method return either a MockSATSerivce or the real SATService object based on your needs.
This is where you would use a DI container (some object that stores interface to concrete type mappings) You would bootstrap the container with the types you want. So, for a unit test, you could contrstruct a mock container that registers the MockSATService as the implementer of the IFoo interface.
Then you would as the container for the concrete type but interface
IFoo mySATService = Container.Resolve<IFoo>();
Then at runtime you would just change out the container so that it bootstraps with the runtime types instead of the mock types but you code would stay the same (Because you are treating everything as IFoo instead SATService)
Does that make sense?
Over time I found that an interesting way to do this is by extracting an interface and creating a wrapper class. This adapts well to a IoC container and also works fine without one.
When testing, create the class passing a fake service. When using it normally, just call the empty constructor, which might simply construct a provider or resolve one using a config file.
public DataService : IDataService
{
private IDataService _provider;
public DataService()
{
_provider = new RealService();
}
public DataService(IDataService provider)
{
_provider = provider;
}
public object GetAllQuestions()
{
return _provider.GetAllQuestions();
}
}
We have a number of castle windsor components declared in a config file.
Some of the components somewhere deep inside might require the services of other components.
The problem is when the application is being closed and the Container is being disposed. During Dispose()/Stop() of the Startable/Disposable component (A) when it requires the services of some other component (B) ComponentNotFoundException then raised. By that time B is already removed from the container.
I've noticed that the order of components declarations in app config file is important. And reodering A and B solves the problem.
Is there a better way to influence the order in which the components are disposed?
Edited:
Following a request in comments I provide here a sample code that will throw ComponentNotFoundException:
class Program
{
static void Main()
{
IoC.Resolve<ICriticalService>().DoStuff();
IoC.Resolve<IEmailService>().SendEmail("Blah");
IoC.Clear();
}
}
internal class CriticalService : ICriticalService, IStartable
{
public void Start()
{}
public void Stop()
{
// Should throw ComponentNotFoundException, as EmailService is already disposed and removed from the container
IoC.Resolve<IEmailService>().SendEmail("Stopping");
}
public void DoStuff()
{}
}
internal class EmailService : IEmailService
{
public void SendEmail(string message)
{
Console.WriteLine(message);
}
public void Dispose()
{
Console.WriteLine("EmailService Disposed.");
GC.SuppressFinalize(this);
}
}
internal interface ICriticalService
{
void DoStuff();
}
internal interface IEmailService : IDisposable
{
void SendEmail(string message);
}
public static class IoC
{
private static readonly IWindsorContainer _container = new WindsorContainer(new XmlInterpreter());
static IoC()
{
_container.AddFacility<StartableFacility>();
// Swapping the following 2 lines resolves the problem
_container.AddComponent<ICriticalService, CriticalService>();
_container.AddComponent<IEmailService, EmailService>();
}
public static void Clear()
{
_container.Dispose();
}
public static T Resolve<T>()
{
return (T)_container[typeof(T)];
}
}
Note: See a comment in the code how swapping the order of inserting components in the container solves the problem.
By having a static IoC class you're actually using the container as a service locator, thus losing most of the benefits of dependency injection.
The problem is that without a proper injection, Windsor doesn't know about the CriticalService - IEmailService dependency, so it can't ensure the proper order of disposal.
If you refactor to make this dependency explicit, Windsor disposes the components in the correct order:
internal class CriticalService : ICriticalService, IStartable
{
private readonly IEmailService email;
public CriticalService(IEmailService email) {
this.email = email;
}
...
}
Here's how it would look like after refactoring.
I, personally, feel that any system that requires Dispose() to be called in a specific order has a flaw in the design.
Dispose() should always be safe to call. The errors should only occur if a component is used after disposal, and then ObjectDisposedException makes the most sense. In a case like this, I would rework your components so that they don't use other componetry during their Dispose() method (it really should be about cleaning each component's own, private resources). This would eliminate this issue entirely.
I am using the Unity IoC container, and I need to intercept any calls to Resolve for a certain base interface, and run my own custom code to construct those types.
In other words, in the sample code below, when I call container.Resolve<IFooN>(), if it hasn't got an instance of the concrete implementing type, it calls MyFactoryFunction to construct one, otherwise I want it to return the cached copy.
The standard Unity container is not able to construct these objects (update: because they are .NET remoting objects, so the concrete classes do not exist in any assembly on the local computer), and I don't want to create them up front and store them with RegisterInstance.
interface IFoo : IBase { ... }
interface IFoo2 : IBase { ... }
...
container.Resolve<IFoo2>();
...
IBase MyFactoryFunction(Type t)
{
...
}
I'm assuming I can create a Unity extension to do this, but I was wondering if there is already a solution out there I can borrow.
For completeness, I should add another answer that works under Unity 2, since my other answer no longer works. It is slightly more involved since you need to make a custom builder policy. Thanks to ctavares from the Unity project who provided lots of help on this thread in implementing this:
public class FactoryUnityExtension : UnityContainerExtension
{
private ICustomFactory factory;
private CustomFactoryBuildStrategy strategy;
public FactoryUnityExtension(ICustomFactory factory)
{
this.factory = factory;
}
protected override void Initialize()
{
this.strategy = new CustomFactoryBuildStrategy(factory, Context);
Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);
Context.Policies.Set<ParentMarkerPolicy>(new ParentMarkerPolicy(Context.Lifetime), new NamedTypeBuildKey<ParentMarkerPolicy>());
}
}
public class ParentMarkerPolicy : IBuilderPolicy
{
private ILifetimeContainer lifetime;
public ParentMarkerPolicy(ILifetimeContainer lifetime)
{
this.lifetime = lifetime;
}
public void AddToLifetime(object o)
{
lifetime.Add(o);
}
}
public interface ICustomFactory
{
object Create(Type t);
bool CanCreate(Type t);
}
public class CustomFactoryBuildStrategy : BuilderStrategy
{
private ExtensionContext baseContext;
private ICustomFactory factory;
public CustomFactoryBuildStrategy(ICustomFactory factory, ExtensionContext baseContext)
{
this.factory = factory;
this.baseContext = baseContext;
}
public override void PreBuildUp(IBuilderContext context)
{
var key = (NamedTypeBuildKey)context.OriginalBuildKey;
if (factory.CanCreate(key.Type) && context.Existing == null)
{
context.Existing = factory.Create(key.Type);
var ltm = new ContainerControlledLifetimeManager();
ltm.SetValue(context.Existing);
// Find the container to add this to
IPolicyList parentPolicies;
var parentMarker = context.Policies.Get<ParentMarkerPolicy>(new NamedTypeBuildKey<ParentMarkerPolicy>(), out parentPolicies);
// TODO: add error check - if policy is missing, extension is misconfigured
// Add lifetime manager to container
parentPolicies.Set<ILifetimePolicy>(ltm, new NamedTypeBuildKey(key.Type));
// And add to LifetimeContainer so it gets disposed
parentMarker.AddToLifetime(ltm);
// Short circuit the rest of the chain, object's already created
context.BuildComplete = true;
}
}
}
Update This answer was for Unity 1.2. For a solution that works with Unity 2, see my other answer.
OK, I have implemented the extension myself. In the builder I cache the object as I want it to be a singleton w.r.t my container. The reason for baseContext is that I want it to be cached in the top level container rather than in any child containers from which it was requested.
public class FactoryMethodUnityExtension<T> : UnityContainerExtension
{
private Func<Type,T> factory;
public FactoryMethodUnityExtension(Func<Type,T> factory)
{
this.factory = factory;
}
protected override void Initialize()
{
var strategy = new CustomFactoryBuildStrategy<T>(factory, this.Context);
Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);
}
}
public class CustomFactoryBuildStrategy<T> : BuilderStrategy
{
private Func<Type,T> factory;
private ExtensionContext baseContext;
public CustomFactoryBuildStrategy(Func<Type,T> factory, ExtensionContext baseContext)
{
this.factory = factory;
this.baseContext = baseContext;
}
public override void PreBuildUp(IBuilderContext context)
{
var key = (NamedTypeBuildKey)context.OriginalBuildKey;
if (key.Type.IsInterface && typeof(T).IsAssignableFrom(key.Type))
{
object existing = baseContext.Locator.Get(key.Type);
if (existing == null)
{
// create it
context.Existing = factory(key.Type);
// cache it
baseContext.Locator.Add(key.Type, context.Existing);
}
else
{
context.Existing = existing;
}
}
}
}
Adding the extension is quite simple:
MyFactory factory = new MyFactory();
container = new UnityContainer();
container.AddExtension(new FactoryMethodUnityExtension<IBase>(factory.Create));
Unity (v2) allows you to specify a factory. It allows a couple of different functions, including taking the type to build up/ name, etc. Simple example:
UnityContainer cont = new UnityContainer();
have a simple create test method - but this can be expanded with whatever factory you want.
this will circumvent the normal creation process which is (for the sake of brevity) call the
longest constructor
all later behaviors including propert setting will still be executed.
cont.RegisterType<TestClass>(new InjectionFactory(c => CreateTest()));
var svc = cont.Resolve<TestClass>();
The Unity container already acts as a factory that knows how to construct (and perform dependency injection for) arbitrary types, so your factory that accepts a Type t appears redundant. Can you elaborate more on why this is not possible?
If this is truly not possible (more likely just too much work), then perhaps you can register your factory with the container instead?