Is there a way to inject into an extension? [duplicate] - c#

I'm using Microsoft Unity as my IoC container. I have a number of extension classes which adds useful methods to my business objects
This is the sort of code I use today:
public static class BusinessObjectExtensions
{
public static bool CanDoStuff(this BusinessObject obj)
{
var repository = BusinessHost.Resolver.Resolve<IRepository>();
var args = new EArgument { Name = obj.Name };
return repository.AMethod(obj.UserName, args);
}
}
Is there a better way to manage dependency injection for extension classes?

The de facto default way of Dependency Injection by Constructor Injection is not possible for static classes. It would be possible to use Parameter Injection like below, however that is not a very clean way.
public static class BusinessObjectExtensions
{
public static bool CanDoStuff(this BusinessObject obj, IRepository repository)
{
var args = new EArgument { Name = obj.Name };
return repository.AMethod(obj.UserName, args);
}
}

You should actually try to avoid extensionmethods unless they only work on internal data (properties in the class itself), or simple datatypes provided in the method. You should not talk to other dependencies in your extension methods. If you follow this rule, you should not need to inject extension-classes with your IoC at all.

Why would you do that?
This raises the coupling in your application to the roof and can be very confusing for your teammates to use the extension method (they'll have to keep in mind to inject the repository each time the method is used).
Instead, create a separate class and use constructor injection to inject the IRepository instance:
public class StuffExecuter
{
private readonly IRepository _repository;
public StuffExecuter(IRepository repository)
{
_repository = repository;
}
public bool CanExecute(BusinessObject obj)
{
_repository.Add(obj.UserName, new EArgument
{
Name = obj.Name
});
}
}

Related

How to mock classes with internal constructors and static factory method?

I have class MyService that depends on ABCService (Nuget package/sdk)
public class MyService
{
private readonly ABCService _abc;
public MyService(ABCService abc)
{
this._abc = abc;
}
public async Task Run(string id)
{
// some logic
var result = await this._abc.DoSomething(id);
// some logic
}
}
ABCService looks something like this:
public class ABCService
{
internal ABCService(string someConnectionString, object someSettings)
{
// ... initialization
}
public static CreateFromConnectionString(string someConnectionString, object someSettings)
{
// some logic
return new ABCService(someConnectionString, someSettings);
}
}
Mocking class this way would not work and throws exception. "Parent does not have a default constructor."
var mock = new Mock<ABCService>();
var myService = new MyService(mock.Object);
How should I approach this? Is there a way to mock such classes?
The only thing that comes to my mind is creating interface IABCService and then injecting it in the constructor of MyService
public class IABCService
{
Task DoSomething(string id);
}
public class MyService
{
private readonly IABCService _abc;
public MyService(IABCService abc)
{
this._abc = abc;
}
}
And then I could do this:
var mock = new Mock<IABCService>();
var myService = new MyService(mock.Object);
Popular isolation frameworks such as Moq, NSubstitute or FakeItEasy are constrained. They can substitute only virtual methods. To use them, you will have to use the interface, as you already guessed. This is the recommended way to easily maintain loose coupling and testability.
There are bunch of unconstrained mocking frameworks: TypeMock Isolator, JustMock, Microsoft Fakes (all three are paid) and free open source Prig, Pose, Shimmy, Harmony, AutoFake, Ionad.Fody, MethodRedirect. They allow to mock non-virtual members, including private, static, etc.
Some of them allow you to work wonders, but you should not get too carried away with using them, because in the end it can lead to bad architecture.

Dependency Injection: how do I integrate values received from method parameters into dependencies that I want to resolve as constructor parameters?

Please bear with me - this is a complicated question, and I've simplified it as much as I am able. (I'm using ASP.NET web API and AutoFac and omitted a bunch of configuration for brevity.)
My goal is to maximize the extent to which dependency-injection is handled by a DI framework, in a situation where not all dependencies of some objects can be known until runtime.
Our players are:
a CONTROLLER class that accepts web requests, the entry point to the app - the input includes repoName
a REPOSITORY RESOLVER class, a factory that resolves a repoName into a specific REPOSITORY. Here's its implementation:
public class RepositoryResolver : IRepositoryResolver
{
public IRepository Resolve(string repoName)
{
return new Repository(new Input { RepoName = repoName });
}
}
a REPOSITORY class (representing a DB or whatever). Here's its implementation:
public class Repository : IRepository
{
private readonly Input input; // proxy for connection string or other identifying information
public Repository (Input input)
{
this.input = input;
}
public string[] Get()
{
return new[] { "I", "am", "a", input.RepoName };
}
}
a BUSINESS LOGIC class that computes a result. The BUSINESS LOGIC class depends on a single repository; it knows nothing of multiple repositories or the repository resolver because it's not concerned with them. Here's its implementation:
public class BusinessLogic : IBusinessLogic
{
private readonly IRepository repository;
public BusinessLogic(IRepository repository)
{
this.repository = repository;
}
public string[] Compute()
{
return repository.Get();
}
}
Procedurally, what I'm trying to accomplish (in this stripped-down toy example) is very straightforward. Here's an example implementation of the controller:
Proposed Answer #1 - Pure DI (no container)
public class PureDIController : ApiController
{
public ProceduralValuesController() { }
public IEnumerable<string> Get(string repoName)
{
IRepositoryResolver repoSource = new RepositoryResolver();
IRepository repo = repoSource.Resolve(repoName);
IBusinessLogic businessLogic = new BusinessLogic(repo);
return businessLogic.Compute();
}
}
...and this works, but obviously I'm not using a DI container here. When using pure DI like this, changes to one player tend to have ripple effects beyond its immediate collaborators and potentially through many layers (not represented here); I feel like moving this composition logic into a DI container will reduce a lot of that type of refactoring. That's the value proposition of this question.
However, when I try to rewrite this class using dependency-injection, I encounter a problem: the BUSINESS LOGIC depends on the REPOSITORY, so it cannot be resolved by a pre-created DI container. Hence, I cannot resolve the hand-waving comment here:
public class DIValuesController : ApiController
{
private readonly IRepositoryResolver repoSource;
private readonly IBusinessLogic businessLogic;
public DIValuesController(
IRepositoryResolver repoSource,
IBusinessLogic businessLogic)
{
this.repoSource = repoSource;
this.businessLogic = businessLogic;
}
public IEnumerable<string> Get(string repoName)
{
var repo = repoSource.Resolve(repoName);
/* ...handwaving to integrate repo into businessLogic... */
return businessLogic.Compute();
}
}
...because IBusinessLogic cannot be resolved at the time the controller is instantiated.
I've developed several possible solutions, and I will add them as potential answers. However, I don't like any of them, hence the post. ¯_(ツ)_/¯ Please surprise me with something I haven't thought of yet!
Yet another possibility - pass IBusinessLogic to Controller not as an instance, but as a factory (i.e. Func<string, IBusinessLogic>) and in Methode Compute Fall factory with repoName.
See, for example:
https://autofaccn.readthedocs.io/en/latest/advanced/delegate-factories.html
Answer #2 - Pass parameters as necessary
This solution abandons the original premise that we can fruitfully convert a method parameter into a constructor parameter. Instead, it assumes that the repoName (or some equivalent differentiator) will need to be passed into any function that requires that information. Here's one possible example implementation of the controller (note that BusinessLogic now requires an additional parameter):
public class ParameterPassingController : ApiController
{
private readonly IBusinessLogic businessLogic;
public ParameterPassingController(
IBusinessLogic businessLogic)
{
this.businessLogic = businessLogic;
}
public IEnumerable<string> Get(string repoName)
{
return businessLogic.Compute(repoName);
}
}
And here's the new implementation of BusinessLogic:
public class BusinessLogic : IBusinessLogic
{
private readonly IRepositoryResolver repositoryResolver;
public BusinessLogic(IRepository repositoryResolver)
{
this.repositoryResolver = repositoryResolver;
}
public string[] Compute(string repoName)
{
var repo = repositoryResolver.Resolve(repoName);
return repo.Get();
}
}
This solution feels very awkward because it modifies the BusinessLogic class to depend on a less direct object than it did before. A class's dependencies should be determined by the class, not by the needs of the caller. The BusinessLogic class was better the way it was before, and any solution that causes us to make it more complicated is probably not a good one.
Answer #3 - Introduce additional resolvers
This solution adds a BUSINESS LOGIC RESOLVER, using the same pattern as the REPOSITORY RESOLVER. (Factory pattern?)
public class BusinessLogicResolverController : ApiController
{
private readonly IRepositoryResolver repoSource;
private readonly IBusinessLogicResolver businessLogicSource;
public BusinessLogicResolverController(
IRepositoryResolver repoSource,
IBusinessLogicResolver businessLogicSource)
{
this.repoSource = repoSource;
this.businessLogicSource = businessLogicSource;
}
public IEnumerable<string> Get(string repoName)
{
var repo = repoSource.Resolve(repoName);
var businessLogic = businessLogicSource.Resolve(repo);
return businessLogic.Compute();
}
}
The thing I don't like about this is that if there are many classes that depend on a single IRepository (and in my non-trivial example, there are many), I need to create a Resolver for each of them. That also complicates other things that DI containers can help with like decorator application and stuff.
Answer #4 - Introduce temporal coupling
This solution replaces the registered implementation of IRepository with a class that also implements IRepositoryManager, allowing it to be pointed at the appropriate repo at runtime. Here's what the controller looks like now:
public class TemporallyCoupledController : ApiController
{
private readonly IRepositoryManager repoManager;
private readonly IBusinessLogic businessLogic;
public TemporallyCoupledController(
IRepositoryManager repoManager,
IBusinessLogic businessLogic)
{
this.repoManager = repoManager;
this.businessLogic = businessLogic;
}
public IEnumerable<string> Get(string repoName)
{
repoManager.Set(repoName);
return businessLogic.Compute();
}
}
...and here's the implementation of IRepositoryManager:
public class RepositoryManager : IRepositoryManager, IRepository
{
private readonly IRepositoryResolver resolver;
private IRepository repo = null;
public RepositoryManager(IRepositoryResolver resolver)
{
this.resolver = resolver;
}
void IRepositoryManager.Set(string repoName)
{
this.repo = resolver.Resolve(repoName);
}
string[] IRepository.Get()
{
if (repo == null)
throw new InvalidOperationException($"{nameof(IRepositoryManager.Set)} must be called first.");
else
return repo.Get();
}
}
This solution certainly allows the controller to stay small, but in my experience, temporal coupling almost always hurts more than it helps. Also, it's unclear that these two lines in the controller have anything to do with each other:
repoManager.Set(repoName);
return businessLogic.Compute();
...but obviously they do. So this is a pretty bad solution.
Answer #5 - Inject the parameter-based dependency inside the controller
This solution makes the controller part of the composition root, rather than having it be resolved by dependency injection. (The line where the built container is retrieved could be done in other ways, but that's not the important part - the main idea is that we need to access its BeginLifetimeScope method directly after we have the input parameters.)
public class SelfAwareDIController : ApiController
{
public SelfAwareDIController() { }
public IEnumerable<string> Get(string repoName)
{
var container = (AutofacWebApiDependencyResolver)GlobalConfiguration.Configuration.DependencyResolver;
using (var scope = container.Container.BeginLifetimeScope(builder =>
builder.RegisterInstance(new Input { RepoName = repoName }).AsSelf()))
{
var businessLogic = scope.Resolve<IBusinessLogic>();
return businessLogic.Compute();
}
}
}
This solution avoids temporal coupling (since businessLogic cannot exist outside the lifetime scope where it can be resolved). It also allows us to remove the REPOSITORY RESOLVER; I was already uncomfortable with REPOSITORY RESOLVER because it's an expansion of the Composition Root that interferes with the DI container's centralized handling of object creation. A downside is that it moves some of the container-related code into the controller rather than keeping it all in the service configuration. (Again, in a non-trivial example there may be many controllers that need to implement similar logic.) It also prevents the controller itself from being instantiated by the DI container (which you can do with AutoFac.WebApi2 package). Still, because it restricts the knowledge of this new context to the controller (and removes the necessity of having a factory class), this is probably the least objectionable of the solutions that I've identified.

Ninject Contextual Binding at runtime depending on a specific value [duplicate]

If I have the following code:
public class RobotNavigationService : IRobotNavigationService {
public RobotNavigationService(IRobotFactory robotFactory) {
//...
}
}
public class RobotFactory : IRobotFactory {
public IRobot Create(string nameOfRobot) {
if (name == "Maximilian") {
return new KillerRobot();
} else {
return new StandardRobot();
}
}
}
My question is what is the proper way to do Inversion of Control here? I don't want to add the KillerRobot and StandardRobot concretes to the Factory class do I? And I don't want to bring them in via a IoC.Get<> right? bc that would be Service Location not true IoC right? Is there a better way to approach the problem of switching the concrete at runtime?
For your sample, you have a perfectly fine factory implementation and I wouldn't change anything.
However, I suspect that your KillerRobot and StandardRobot classes actually have dependencies of their own. I agree that you don't want to expose your IoC container to the RobotFactory.
One option is to use the ninject factory extension:
https://github.com/ninject/ninject.extensions.factory/wiki
It gives you two ways to inject factories - by interface, and by injecting a Func which returns an IRobot (or whatever).
Sample for interface based factory creation: https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface
Sample for func based: https://github.com/ninject/ninject.extensions.factory/wiki/Func
If you wanted, you could also do it by binding a func in your IoC Initialization code. Something like:
var factoryMethod = new Func<string, IRobot>(nameOfRobot =>
{
if (nameOfRobot == "Maximilian")
{
return _ninjectKernel.Get<KillerRobot>();
}
else
{
return _ninjectKernel.Get<StandardRobot>();
}
});
_ninjectKernel.Bind<Func<string, IRobot>>().ToConstant(factoryMethod);
Your navigation service could then look like:
public class RobotNavigationService
{
public RobotNavigationService(Func<string, IRobot> robotFactory)
{
var killer = robotFactory("Maximilian");
var standard = robotFactory("");
}
}
Of course, the problem with this approach is that you're writing factory methods right inside your IoC Initialization - perhaps not the best tradeoff...
The factory extension attempts to solve this by giving you several convention-based approaches - thus allowing you to retain normal DI chaining with the addition of context-sensitive dependencies.
The way you should do:
kernel.Bind<IRobot>().To<KillingRobot>("maximilliam");
kernel.Bind<IRobot>().To<StandardRobot>("standard");
kernel.Bind<IRobotFactory>().ToFactory();
public interface IRobotFactory
{
IRobot Create(string name);
}
But this way I think you lose the null name, so when calling IRobotFactory.Create you must ensure the correct name is sent via parameter.
When using ToFactory() in interface binding, all it does is create a proxy using Castle (or dynamic proxy) that receives an IResolutionRoot and calls the Get().
I don't want to add the KillerRobot and StandardRobot concretes to the Factory class do I?
I would suggest that you probably do. What would the purpose of a factory be if not to instantiate concrete objects? I think I can see where you're coming from - if IRobot describes a contract, shouldn't the injection container be responsible for creating it? Isn't that what containers are for?
Perhaps. However, returning concrete factories responsible for newing objects seems to be a pretty standard pattern in the IoC world. I don't think it's against the principle to have a concrete factory doing some actual work.
I was looking for a way to clean up a massive switch statement that returned a C# class to do some work (code smell here).
I didn't want to explicitly map each interface to its concrete implementation in the ninject module (essentially a mimic of lengthy switch case, but in a diff file) so I setup the module to bind all the interfaces automatically:
public class FactoryModule: NinjectModule
{
public override void Load()
{
Kernel.Bind(x => x.FromThisAssembly()
.IncludingNonPublicTypes()
.SelectAllClasses()
.InNamespaceOf<FactoryModule>()
.BindAllInterfaces()
.Configure(b => b.InSingletonScope()));
}
}
Then create the factory class, implementing the StandardKernal which will Get the specified interfaces and their implementations via a singleton instance using an IKernal:
public class CarFactoryKernel : StandardKernel, ICarFactoryKernel{
public static readonly ICarFactoryKernel _instance = new CarFactoryKernel();
public static ICarFactoryKernel Instance { get => _instance; }
private CarFactoryKernel()
{
var carFactoryModeule = new List<INinjectModule> { new FactoryModule() };
Load(carFactoryModeule);
}
public ICar GetCarFromFactory(string name)
{
var cars = this.GetAll<ICar>();
foreach (var car in cars)
{
if (car.CarModel == name)
{
return car;
}
}
return null;
}
}
public interface ICarFactoryKernel : IKernel
{
ICar GetCarFromFactory(string name);
}
Then your StandardKernel implementation can get at any interface by the identifier of you choice on the interface decorating your class.
e.g.:
public interface ICar
{
string CarModel { get; }
string Drive { get; }
string Reverse { get; }
}
public class Lamborghini : ICar
{
private string _carmodel;
public string CarModel { get => _carmodel; }
public string Drive => "Drive the Lamborghini forward!";
public string Reverse => "Drive the Lamborghini backward!";
public Lamborghini()
{
_carmodel = "Lamborghini";
}
}
Usage:
[Test]
public void TestDependencyInjection()
{
var ferrari = CarFactoryKernel.Instance.GetCarFromFactory("Ferrari");
Assert.That(ferrari, Is.Not.Null);
Assert.That(ferrari, Is.Not.Null.And.InstanceOf(typeof(Ferrari)));
Assert.AreEqual("Drive the Ferrari forward!", ferrari.Drive);
Assert.AreEqual("Drive the Ferrari backward!", ferrari.Reverse);
var lambo = CarFactoryKernel.Instance.GetCarFromFactory("Lamborghini");
Assert.That(lambo, Is.Not.Null);
Assert.That(lambo, Is.Not.Null.And.InstanceOf(typeof(Lamborghini)));
Assert.AreEqual("Drive the Lamborghini forward!", lambo.Drive);
Assert.AreEqual("Drive the Lamborghini backward!", lambo.Reverse);
}

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!

Require Factory class in Extension Method

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.

Categories

Resources