Openrasta: Swap instance in dependency resolver - openrasta

Suppose I register some instance in OpenRasta's dependency resolver using
resolver.AddDependencyInstance(IInterface, instance, DependencyLifetime.Singleton)
Now if I want to swap that instance later, say to reread fresh data from the db, is another call to resolver.AddDependencyInstance the right thing to do?
Checking the InternalDependencyResolver implementation, it seems to be fine. However I'm asking because the behavior is not defined (in openrasta's sources, where I checked), and the method prefix "Add" is suggestive of different behavior.

I wouldn't use Singleton if you have to swap the instance at some point.
Use DependencyLifetime.Transient and have a constructor injection in the class where you need the new instance

Related

Supply Context to DbMigrator

How DbMigrator works
I have code that instantiates a new DbMigrator(new Configuration())
Configuration is a custom extension of DbMigrationsConfiguration<T>, where T is DbContext
So within Configuration, there is a ContextType, which is equal to <T>.
When DbMigrator is instantiated, it attempts to create an instance of the <T> DbContext. It will either try to use an Empty Constructor on the <T> Context, or it will attempt to look for an implementation of IDbContextFactory<...> where ... is the actual type of , but not generic T.
How DbMigrator Doesn't Work
The problem is, the assembly instantiating DbMigrator has no access to the specific typed IDbContextFactory<...> that it needs to discover. Also, my DbContext has no default constructor, and I don't want it to. So I receive the exception The target context '...' is not constructible.
The thing that bothers me is, at the point I am instantiating DbMigrator, I already have an instance (or may already be within an instance) of the DbContext I am migrating. Also, I have access to a generic IDbContextFactory<T> that is not discoverable by DbMigrator's internals, but I'd be happy to provide it an instance.
The Question
So how do I tell DbMigrator to either just use my Context instance, or use an instance of a IDbContextFactory I specify? When it relies on its magic juju behind the scenes to try to discover these things (presumably using reflection/ServiceLocation) it is failing.
My Situation
Within one AppDomain, I am using n Contexts. I'd like to say one, but it's typically two, and may be more than that. So any solution that relies on a single app/web config property, or an attribute decorator, which points to a single DbConfiguration or ConnectionFactory won't work for me. Because there can only be one per AppDomain and, unless I could configure it based contextually on which Context I'm needing at the time, it is futile. So there's wiggle room there, but I dunno.
Also, there may be some juju I don't understand about EF relating to the base constructor. But I don't believe passing a DbConnection into the constructor instead of a nameOrConnectionString would work. It is still not an empty constructor. But if there's something EF does to search for constructors with that, and how to utilize it, that MIGHT work.

Singleton Vs Singleton Factory

We have a system which has a lot of model objects (e.g. Car, Pedestrian, Road, ...)
Currently all of them have managers (CarManager, PedestrianManager, RoadManager) that return a singleton of the respective class.
An alternative proposed is to have a ManagerFactory singleton that can return instances of CarManager, PedestrianManager, RoadManager. (e.g. ManagerFactory.getInstance().getCarManager())
We also write test for the project and the concern was that if we will use Dependency Injection we will need an actual instance of an object to inject managers.
Is this alternative a good one? Would you change the singleton into something else in this case?
A singleton directly or a singleton factory are basically the same thing - an opaque reference to something - a hidden dependency. With a global text search you can find these dependencies so neither option makes the situation better or worse.
Dependency injection means that you're publicly declaring that for instance A to work it needs an instance of B (or an instance which conforms to protocol C is a better dependency situation). This requires that you instantiate B somewhere and pass it to A.
From a test point of view dependency injection is far superior, because you generally want to create a mock version of B and use that to test A. The test injects the instance to use. Testing singletons is a pain...
So, ideally, the first class involved would create an instance of B and pass it to the other classes that need it, and that instance gets passed on from there.

Typhoon: Injecting run-time arguments into a singleton

I'm trying to figure out how to inject run-time arguments into a singleton when it is created, and then have those arguments just be remembered from then on. I'm not sure if the interface for run-time arguments can support this, though. Say, for example, I have a Client object that requires a token, and has the following initializer:
+ (instancetype)initWithToken:(NSString *)token;
The token is obtained at runtime from the server and is different for every user, so I can't simply put the NSString in the definition. So I create the following method on my Typhoon assembly:
- (Client *)clientWithToken:(NSString *)token;
However, in the future (when I'm injecting this client into other classes), I won't have the token on hand to call this method with. So I would like to just be able to inject [self client], for example. Since the client is a singleton and has already been created, the token isn't necessary, anyway.
However, I can't seem to find a way to do this. Obviously, defining a separate method called client would just return a different client. Can I just call clientWithToken:nil and the argument will be ignored if the client already exists? Perhaps traversing the assembly's singletons array would work, but that is obviously very inelegant.
I have considered injecting by type (so I don't need a method to call), but I have multiple different clients of the same type, so I need to be explicit about which client to inject. Of course, there is also the option of removing this parameter from the initializer, and instead setting it as a property from outside the assembly; however this pattern is used throughout our application, so I would like to avoid rewriting that much code.
Thank you.
Reviewing the Typhoon User Guide's 'When to Use Runtime Arguments' shows that this scenario isn't really a good match. Runtime arguments are great when we have a top-level component that mixes some static dependencies with information that is known later - thus avoiding the creation of a custom 'factory' class. Its not possible to use them in the way described.
Instead consider the following suggestions:
Inject a shared context class
Create a mutable Session model object and register it with Typhoon. Update the state on this model when you have a token. Inject this into the clients, which will use this session information when making connections.
Aspect Hook
Hook your clients so that before a method is invoked the token information is available. This could be done by:
Using an Aspects library like this one.
Define a Protocol for the clients and wrap the base implementation in one that is security aware.

In Ninject, how can I run custom code on an object after it is created with Bind<..>.ToSelf()?

In Ninject's dependency injection, if you set up a binding of a class to itself like so:
Bind<SomeClass>().ToSelf();
Ninject very nicely resolves any dependencies SomeClass has and gives you the object back. I want to be able to do something to the SomeClass it returns every time it creates a new one, so like a post-processing event. I could use the .ToMethod (or ToFactoryMethod) binding to explicitly new it up, but I would like all its dependencies resolved by Ninject beforehand.
It wouldu be nice to do something like:
Bind<SomeClass>()
.ToSelf()
.After(sc => sc.MethodIWantToCall()); // then after here, Ninject returns the object.
Is there some way to do this in Ninject 1.0/1.1?
If you can't put the code you want to execute in the constructor, you can implement IInitializable or IStartable. The former provides an Initialize() method that gets called after all injection has completed, and the latter provides both a Start() and Stop() method, called during activation and deactivation, respectively.
I ran into the same problem, but I could not use Nate's solution because I couldn't make the type implement IInitializable. If you're in a similar boat, you can use .OnActivation and avoid having to modify the definition of the target types:
Bind<SomeClass>().ToSelf().OnActivation(x => ((SomeClass)x).MyInitialize());
You can see how we call some arbitrary initialization method (MyInitialize) upon activation (instantiation) of the class.
This has the advantage of not baking in a hard dependency to Ninject in your own classes (aside from your modules, of course), thus allowing your types to remain agnostic about the DI-framework you end up using.

Can Autofac do automatic self-binding?

I know some DI frameworks support this (e.g. Ninject), but I specifically want to know if it's possible with Autofac.
I want to be able to ask an Autofac container for a concrete class, and get back an instance with all appropriate constructor dependencies injected, without ever registering that concrete class. I.e., if I never bind it explicitly, then automatically bind the concrete class to itself, as if I had called builder.Register<MyClass>();
A good example of when this would be useful is ViewModels. In MVVM, the layering is such that only the View depends on the ViewModel, and that via loose typing, and you don't unit-test the View anyway. So there's no need to mock the ViewModel for tests -- and therefore there's no reason to have an interface for each ViewModel. So in this case, the usual DI pattern of "register this interface to resolve to this class" is unnecessary complexity. Explicit self-binding, like builder.Register<MyClass>();, also feels like an unnecessary step when dealing with something as straightforward as a concrete class.
I'm aware of the reflection-based registration example in the Autofac docs, but that's not to my taste either. I don't want the complexity (and slowness) of registering every possible class ahead of time; I want the framework to give me what I need when I need it. Convention over configuration, and all that.
Is there any way to configure Autofac so it can say "Oh, this is a concrete type, and nobody registered it yet, so I'll just act like it had been registered with default settings"?
builder.RegisterTypesMatching(type => type.IsClass)
If you look at the source you will see that RegisterTypesMatching (and RegisterTypesFromAssembly) is NOT DOING ANY REFLECTION. All Autofac is doing in this case is registering a rule that accepts a type or not. In my example above I accept any type that is a class.
In the case of RegisterTypesFromAssembly, Autofac registers a rule that says "if the type you're trying to resolve have Assembly == the specified assembly, then I will give you an instance".
So:
no type reflection is done at register time
any type that matches the criteria will be resolved
Compared to register the concrete types directly, this will have a perf hit at resolve time since Autofac will have to figure out e.g. constructor requirements. That said, if you go with default instance scope, which is singleton, you take the hit only the first time you resolve that type. Next time it will use the already created singleton instance.
Update: in Autofac 2 there is a better way of making the container able to resolve anything. This involves the AnyConcreteTypeNotAlreadyRegistered registration source.
what about:
builder.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly());
no reflection is done, as Peter Lillevold points out.

Resources