Statics are inaccessible from within dynamically loaded Controller - c#

I have a plugin system here that checks assemblys for implementations of a base class. One base class is supposed to provide an API, but when I hit a Controller, static variables forget their values and always return their default value.
The plugin system creates module instances like this:
var assembly = Assembly.LoadFile(#"absolute\path\to\TestModule.dll");
var types = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ModuleBase)));
ModuleBase instance = (ModuleBase)Activator.CreateInstance(types.FirstOrDefault());
instance.Execute();
That's working nice so far. The plugin base type is as minimal as it could get:
public abstract class ModuleBase
{
public abstract void Execute();
}
Now I implement a plugin for that in a different project:
public class TestModule : ModuleBase
{
public static int StaticTest;
public override void Execute()
{
StaticTest = 3; // variable is initialized with some non-default value
WebHost.CreateDefaultBuilder()
.UseStartup<Startup>()
.Build()
.RunAsync(cancellationTokenSource.Token);
}
}
with the Startup.cs class looking like this:
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
}
Nothing fancy, really. However, when I now implement a Controller that is accessing my StaticTest variable, it's value is 0:
public class TestController : ControllerBase
{
[Route("Test")]
[HttpGet]
public ActionResult<int> GetStatics()
{
return TestModule.StaticTest;
}
}
If I drop the plugin approach and instead create the WebHost from a console application directly, everything works as expected and the Controller returns 3.
I suspected MVC to launch controllers in a different AppDomain, but that does not seem to be the case, as AppDomain.CurrentDomain.FriendlyName and AppDomain.CurrentDomain.Id do not change and AppDomain.CurrentDomain.DomainUnload is not invoked.
Any ideas are welcome, I am totally clueless now and I feel I missed some essential concept of this whole thing.

You have an ivar named Test, and you're accessing a member named StaticTest, which doesn't seem to be defined. My assumption is that you misnamed the ivar in this question and it's supposed to be StaticTest, not Test.
Based on that assumption, the issue is that you've cast your dynamically created object to ModuleBase, but StaticTest exists on TestModule. Therefore, you cannot access StaticTest unless you cast to TestModule, because that's where it's defined.
EDIT
Sorry, I wasn't paying close enough attention to the controller code. The real issue is similar to the above, but has to do with Execute. You haven't shown where that's called, but I'm assuming you're calling it somewhere or the answer as to why the static has no value would be immensely obvious. However, if your instance is typed as ModuleBase, it's going to call ModuleBase.Execute(), not TestModule.Execute(), even if it's actually a TestModule instance. Only if you're working with something actually typed as TestModule will the correct Execute override be called.

Related

Multiple scopes in the application using Autofac

I have a question concerning lifetime scopes in Autofac.
It is allowed to create multiple scopes in different places in the application to resolve types?
In official documentation there is such a statement:
Note: generally speaking, service location is largely considered an anti-pattern That is, manually creating scopes everywhere and sprinkling use of the container through your code is not necessarily the best way to go. Using the Autofac integration libraries you usually won’t have to do what we did in the sample app above. Instead, things get resolved from a central, “top level” location in the application and manual resolution is rare. Of course, how you design your app is up to you.
What if I have several view models and I need to resolve some types in each one?
Example:
public class ClassA
{
//some code here
}
public class ClassB
{
//some code here
}
public class ClassC
{
//some code here
}
public class ViewModelA
{
public ViewModelA()
{
}
public void Method()
{
//some code here
using (var scope = Container.BeginLifetimeScope())
{
var typeC = scope.Resolve<ClassC>();
//some code here
}
}
}
public class ViewModelB
{
public ViewModelB()
{
}
public void Method()
{
//some code here
using (var scope = Container.BeginLifetimeScope())
{
var typeA = scope.Resolve<ClassA>();
var typeB = scope.Resolve<ClassB>();
//some code here
}
}
}
Assuming that all types are registered in the container - is spreading such scopes across the app is a good practice? How do you understand that?
Best regards.
TL;DR
I have a question concerning lifetime scopes in Autofac. It is allowed to create multiple scopes in different places in the application to resolve types?
Yes, it is allowed, even though it is considered not the best way to go - but definitely not the prohibited one.
What if I have several view models and I need to resolve some types in each one?
Just resolve them through constructor injection as it was suggested by #Raymond. You don't need scopes for something as simple as just resolving stuff.
Now, let's talk this through a little bit.
First of all, how do you use constructor injection? There's nothing simpler than that. Let's modify your example just a bit:
public class ClassA
{
//some code here
}
public class ClassB
{
//some code here
}
public class ClassC
{
//some code here
}
public class ViewModelA
{
private ClassC typeC;
// this is a constructor injection - yes, it's that simple.
public ViewModelA(ClassC _typeC)
{
typeC = _typeC;
}
public void Method()
{
typeC.doStuff();
}
}
public class ViewModelB
{
private ClassA typeA;
private ClassB typeB;
public ViewModelB(ClassA _typeA, ClassB _typeB)
{
typeA = _typeA;
typeB = _typeB;
}
public void Method()
{
typeA.doStuff();
typeB.doAnotherStuff();
}
}
That's it. You just specify parameters in the constructor and save those parameters somewhere in the private fields of the class - and you're good to go. Just use those objects assuming they do exist for sure. (They can be optional though, but I'll skip that for now). If autofac is unable to resolve some dependency it will throw an exception - thus if your class got created you can be absolutely sure that all the dependencies were resolved and provided to it in the constructor parameters. (Again, I'll skip some more complicated scenarios for the sake of brevity and clarity).
What does it give us? Well, now classes ViewModelA and ViewModelB know nothing about any containers or DI in general. All they know is that someone (read: "container") will somehow provide a couple of parameters of specified types (which are usually interfaces) from outside. The class itself now knows nothing about who will create its dependencies, where, when and how - it's not its concern anymore. This is the whole point of dependency injection: removing the concern of managing dependencies.
Next thing is - where are the scopes in this picture? Well... nowhere. :) That's the ideal picture: the services are completely unaware of the existence of the DI container.
But what is a lifetime scope anyways? It is a mean of controlling (surprise!) life time of the objects that are resolved from it. You typically don't need it, unless you are dealing with some edge-case scenarios.
Let's take a look at the extremely simplified example. Say, you have some job that needs to perform some kind of requests to external resources on schedule. However, the method that performs requests is actually generic: it does not know beforehand what exact type of request it is performing because it is defined by the type parameter of the method which will only be known in the runtime.
Also, let's say that you have another requirement: you need to not keep api services in the memory but rather create them only for performing the request and then discard them right away after work is done.
It could look something like the following:
abstract class SomeSpecialApi<TSomeTypeParam> { // just some common base type
public abstract string doGetStuff();
}
class SomeSpecialApi1 : SomeSpecialApi<SomeTypeParam1> where SomeTypeParam1 : TSomeTypeParam {
private HttpClient _client;
public SomeSpecialApi(HttpClient client) {
_client = client;
}
public override string doGetStuff() {
return _client.get(someUrlWeDontCareAbout).Result;
}
}
class SomeSpecialApi2 : SomeSpecialApi<SomeTypeParam2> where SomeTypeParam2 : TSomeTypeParam {
private SomeFtpClient _client;
public SomeSpecialApi(SomeFtpClient client) {
_client = client;
}
public override string doGetStuff() {
// it's just something very different from the previous class
return _client.read(someOtherPathWeDontCareAboutEither).Result;
}
}
class JobPerformer {
private ILifeTimeScope _scope;
public JobPerformer(ILifeTimeScope scope) {
_scope = scope;
}
void PerformJob<T>() {
while (true) {
using (var childScope = scope.BeginLifeTimeScope()) {
var api = childScope.Resolve<SomeSpecialApi<T>>();
var result = api.doGetStuff();
// do something with the result
} // here the childScope and everything resolved from it will be destroyed
// and that's the whole purpose of the lifetime scopes.
Thread.Sleep(1000);
}
}
}
Do you see how it works? Depending on the method's type parameter container will resolve different classes to get the job done. So, instead of creating all the dependencies and then destroying them manually all you need to do is to create your own scope, request an instance of the service you need and then destroy scope after work is done. Scope destruction takes care of destroying all the dependencies which you don't (and shouldn't) even know about. That's definitely an improvement compared to the creation of all the dependencies manually.
However, the disadvantage here is that now JobPerformer class has to know about such a thing as ILifeTimeScope. So it's in some sense similar to the ServiceLocator pattern: we have to know at least who to ask for the dependency, in other words: JobPerformer now knows something about our container. That's what we ideally want to avoid, and there are also other means to achieve it: factories; owned instances; different lifetime policies of service registrations in the container; different kinds of lifetime scopes (at least in autofac); etc.

How to ensure Static Properties get initialized after Global.Application_Start code?

How do I ensure that the Factory class' properties get initialized after Application_Start?
public static class Globals
{
public Static Customer Cust {get;set;}
}
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
Globals.Cust = GetCustomerFromDataBase();
}
}
public static class Factory
{
public static Customer Cust => Globals.Cust ;
}
The Factory.Customer gets called by a method inside a webapi controller.
The answer to your question depends on your code. If as you say, Factory.Cust is first referenced in a WebAPI Controller method, then you should be safe; the Application_Start method should have run before anything in one of your controllers.
Your Factory.Cust property doesn't get initialized. When someone tries to read the value of Factory.Cust, all that happens is that the Globals.Cust property (getter) is executed (remember, properties are really code, not just state). As long as Globals.Cust is initialized before Factory.Cust is read, you are safe. If you test your code (by putting breakpoints here and there) and it seems to follow what I'm saying, you should be OK.
What I was saying in the comments about static classes is that a static class can have a constructor. It can be explicit (you write a constructor for the class), but it can also have other code you have in your class. For example, if, in your Factory class, you had code that looked like:
private static Customer _localCustomerStuff = new Customer();
Then the code that's associated with that field would be folded into the Factory constructor. Property initializers like the one below also do the same kind of thing (since they are initializing the hidden backing store for the property).
public static string SomeString { get; set; } = "SomeString Initial Value";
You don't know exactly when a static class's constructor code will run, but there is a guarantee made by the framework that it will run before any reference to that class is made. If you access the Factory class, and you had some initialization associated with that class (none of which you show in your post above), then you can be sure that the initialization will have started before you access anything to do with the class.
Take a look at Static Constructor Docs to see what I'm talking about.

Deal with standard library types in scope of dependency injection

Consider the following type:
class SomeType
{
public void Configure()
{
var windowsService = new ServiceController("msdtc");
windowsService.Start();
}
}
There are at least three issues.
We have implicit dependency to ServiceController.
We cannot to unit test Configure().
We have a new operator that breaks our DI strategy.
So to fix it we can extract another type and input it to our SomeType.
interface IWindowsService
{
void Start();
}
class WindowsService : IWindowsService
{
private readonly ServiceController _serviceController;
public WindowsService(string serviceName)
{
_serviceController = new ServiceController(serviceName));
}
public void Start() => _serviceController.Start();
}
class SomeType
{
private readonly IWindowsService _msdtcService;
public SomeType(Func<string, IWindowsService> createServiceCallback) //explicit dependency
{
_msdtcService = createServiceCallback.Invoke("msdtc");
}
public void Configure() => _msdtcService.Start();
}
It fixes the issues #1 and #2 but we still have a new operator in the new type WindowsService. I try to understand should I register standart ServiceController in the DI-container or use it directly as demonstrated above (by new)?
container.RegisterType<ServiceController>();
Also I am not sure whether we should try to test WindowsService or maybe it would be better to rewrite it something like this:
class WindowsService : ServiceController, IWindowsService
{
}
Since WindowsService is now just inheriting we cannot test anything here. The type is already tested by Microsoft.
However it breaks incapsulation and maybe ISP from SOLID. Because we can cast IWindowsService to WindowsService or even to ServiceController.
What is the best way to deal with standart stable types?
Please refer me to another question if we have.
Thanks in advance.
interface ISomeInterface
{
void Configure();
}
class SomeType : ISomeInterface
{
public void Configure()
{
var windowsService = new ServiceController("msdtc");
windowsService.Start();
}
}
I would do it like above. Now nothing should directly depend on SomeType. Everything should depend on ISomeInterface. That keeps the dependency on ServiceController limited to a single class.
The new operator really isn't a problem. There's no IServiceController that ServiceController implements, so if you want to use it, you have to tie yourself to it. By hiding it in SomeType which does implement an interface, at least you've limited how many things have a direct dependency on it.
The problem you are dealing with is a subtype of a larger problem, the issue of dealing with system level calls in IoC.
Another example of the problem is the use of DateTime.Now. If you call this in your code, there is no way to isolate it away, which is a problem if you want to test in various time scenarios.
One solution is to abstractify away all system level calls, so that you can substitute your own mock operating system for the purpose of testing. Here is an example for DateTime. I'll provide an example for your specific issue too:
interface IOperatingSystem
{
void StartService(string name);
}
class OperatingSystem : IOperatingSystem
{
public virtual void StartService(string name) {
var windowsService = new ServiceController(name);
windowsService.Start();
}
}
class SomeType : ISomeType
{
private readonly IOperatingSystem _operatingSystem;
public SomeType(IOperatingSystem operatingSystem)
{
_operatingSystem = operatingSystem;
}
public void Configure()
{
_operatingSystem.StartService("msdtc");
}
}
In your IoC container:
container.RegisterType<IOperatingSystem, OperatingSystem>();
container.RegisterType<ISomeType, SomeType>();
Now you can isolate away all you want, just by overriding your operating system class:
class MockOperatingSystem : OperatingSystem
{
public override StartService(string name)
{
//Do something worthy of testing, e.g. return normally or throw an exception
}
}
and register (in your unit tests) like this:
container.RegisterType<IOperatingSystem, MockOperatingSystem>();
Now when you go to code this, you might choose to have different interfaces for different system functions (e.g. maybe you want a IServiceControlManager that is separate from other O/S calls). That is fine, and common. I prefer one big class for all my O/S calls, because I know those O/S calls are not going to change. Well, they might change, but if they do, I have much bigger problems, and rework will be unavoidable anyway.

Registering Generics in Unity

I have some Unity DI in a project that is causing dependency registration unit tests to fail. I think it's because I have the syntax wrong on registering the generics. I suppose it could be something else I'm not seeing. In any case, I tried to follow [this article][1] to register the generics, but I found it lacking and confusing, so I still haven't gotten there. It mentions Unity classes like InjectionConstructor and GenericaParameter but in trying to use these, I'm getting various compile time errors. I'm also not finding anything here on SO to clear things up. I am hoping someone here might have a more clear explanation for how to register these things (or some other answer, if that's not the issue).
Here is some relevant code:
First is my top level interface which will be injected in and used by client code, specifying a type for T.
namespace Elided.Extraction.Interfaces
{
public interface IDataExtractionService<out T>
{
T GetData(Stream stream);
}
}
This next class is the implementation which has an injectable IDataExtractor:
namespace Elided.Extraction
{
public class DataExtractionService<T> : IDataExtractionService<T>
{
private readonly IDataExtractor<T> extractor;
internal DataExtractionService(IDataExtractor<T> extractor)
{
this.extractor = extractor;
}
public T GetData(Stream workbookStream)
{
// elided
return this.extractor.GetData(elidedArgument)
}
}
}
And here's the interface for the IDataExtractor:
namespace Elided.Extraction.Behaviors.Interfaces
{
internal interface IDataExtractor<out T>
{
T GetData(object elidedArgument);
}
}
Here's an implementation of IDataExtractor. It's an implementation of type DataSet, but the idea is that numerous implementations could exist, allowing the client code to have an injectable IDataExtractionService or any other type for which an extractor implementation is written.
namespace Elided.Extraction.Behaviors
{
internal class DataSetExtractor : IDataExtractor<DataSet>
{
public DataSet GetData(object elidedArgument)
{
// implementation elided
// returns a DataSet
}
}
}
And finally, here is my registration code (in the same assembly as the above stuff) which I don't believe is working:
public void RegisterDependencies(IDependencyContainer container)
{
container.RegisterType(typeof(IDataExtractionService<>), typeof(DataExtractionService<>));
container.RegisterType(typeof(IDataExtractor<DataSet>), typeof(DataSetExtractor));
}
Update: The specific error message comes from an Exception throw by a unit test:
Exception occurred while: while resolving. Exception is:
InvalidOperationException - The type DataExtractionService`1
cannot be constructed. You must configure the container to supply this
value. [1]:
https://msdn.microsoft.com/en-us/library/ff660936(v=pandp.20).aspx
I pasted your code and created a unit test:
[TestMethod]
public void TestUnityConfiguration()
{
var container = new UnityContainer();
//This part is copied from your Unity configuration.
container.RegisterType(typeof(IDataExtractionService<>), typeof(DataExtractionService<>));
container.RegisterType(typeof(IDataExtractor<DataSet>), typeof(DataSetExtractor));
var x = container.Resolve<IDataExtractionService<DataSet>>();
Assert.IsInstanceOfType(x, typeof(DataExtractionService<DataSet>));
var y = container.Resolve<IDataExtractor<DataSet>>();
Assert.IsInstanceOfType(y, typeof(DataSetExtractor));
}
The first one failed because DataExtractionService doesn't have a public constructor, so Unity can't create it.
I tried entries in AssemblyInfo.cs to make internals visible to Unity, but that didn't work.
I read some more - there isn't a workaround for hidden constructors. See this post.
You can make the constructor public, but then you'll also need to make IDataExtractor<T> public. With that change I was able to resolve instances of both registrations.

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.

Categories

Resources