Inject IOptionsSnapshot in Block constructor - piranha-cms

I created a new custom Block and wanted to inject an IOptionsSnapshot to read my appsettings.json values. The problem is that I get an error saying there is no parameterless constructor for my custom block.
Is there a way to somehow do this injection or is this a limitation in Piranha and custom blocks.

At the moment neither Fields nor Blocks supports parameter injection into the constructor, however Fields have two initialization methods that both support parameter injection, Init() and InitManager(). Given how models are constructed the easiest solution would probably be to add the corresponding init methods to Blocks as well.
Feel free to open an issue/feature request at the GitHub repo and we can take the discussion from there!

Related

Ninject MockingKernel with Saboteurs

Is it possible to use MockingKernel so that it generates mock objects automatically that, if interacted with, will throw an exception (a.k.a, saboteurs)?
This is useful when you want to get an object with various dependencies, but you know your code should only be interacting with some of them. If you don't explicitly Bind a dependency (via ToMock, etc.), it should return an object that throws an exception the first time it is interacted with.
This is much better than waiting until the code finishes executing, then writing a bunch of checks to make sure you didn't call into a mock.
Does this already exist?
The answer provided above did not indicate how to setup the Ninject MockingKernel using MOQ so that the default behavior is Strict. For the benefit of others, here is what I found.
The Ninject.MockingKernel.Moq namespace provides the class NinjectSettingsExtensions with the methods SetMockBehavior() and GetMockBehavior() that allow you to specify which mocking behavior to use as the global default. I have NOT been able to find any way to override the default for an individual GetMock() request.
using Ninject;
using Ninject.MockingKernel.Moq;
var kernelSettings = new NinjectSettings();
kernelSettings.SetMockBehavior(MockBehavior.Strict);
using(var kernel = new MoqMockingKernel(kernelSettings))
{
var mockFoo = kernel.GetMock<IFoo>(); // mockFoo.Behavior == MockBehavior.Strict
}
I had been using NSubstitute's implementation of MockingKernel. NSubstitute doesn't really support a "strict" mode and you can't configure it through the NSubstituteMockingKernel class.
However, you can configure Moq to do strict mode. Best of all, the MoqMockingKernel class allows you to change the mock behavior globally. This way, any calls that aren't configured result in an exception being thrown.
This is exactly what I was looking for. The only pain was switching from NSubstitute to Moq.

Getting lazy instance via kernel (Ninject)

I am using Ninject in substitution of MEF and I was wondering if it's possible to get lazy instances via standard kernel methods and not via [inject] .
I need this since when building up my application's menu I have to pass all particular view models and then if the user is enabled on that function to add it to the menu
Thanks
Sure thing, you can inject a Lazy<T> and the value will only be instanciated when you access Lazy<T>.Value.
You can also inject a Func<T> and use it to create T whenever you like (with the func, every call creates a new instance).
Of course you can also do IResolutionRoot.Get<Lazy<T>>() or IResolutionRoot.Get<Func<T>>(), but usually that's a sign of bad design (service locator), so use constructor injection when it's feasible.
EDIT: When is the "enabling of the user" happening? Is it a one time thing? What is being displayed before and after?
There might be other/better designs to achieve this but it's hard to say with that little information.

What does Kernel.Inject(instance); actually do?

I am learning to use dependency injection with ninject. Most of the properties and methods are fairly intuitive, one that has me though is Kernel.Inject(instance);
What does the Inject method actually do as it doesn't return anything. I've looked around but search for a method called inject on a dependency injection container is a nightmare, I can't find any references to the method specifically.
Kernel.Inject(instance) will inject dependencies into an already existing object.
That's why it returns void because it takes the parameter object instance and starts to investigate it's methods and property setters looking for the [Inject] attribute. Then it will call them with the resolved instances of their parameter types. (this is called Method or Property injection)
So when contructor injection is not enoughpossible you can Kernel.Inject to fill in your dependencies for a given instance.
You can read more about this here: Ninject Injection Patterns

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.

Asserting a method invocation on one of several injected types

We use RhinoMocks. I have a type into whose constructor 9 types are injected. I'd like a way of automocking the type, but being able to detect a particular method invocation on one of the injected objects (i.e. I only care about a single method invocation on one of the injected objects).
Is this possible, or do I have to manually inject all the mock objects into the constructor?
I haven't seen any frameworks that would auto-create these mocks for you. You can do it in your [SetUp] method, so at least the tests will not be cluttered with boilerplate code.
I need to check out http://autofixture.codeplex.com/. Its not really container specific, there is an extension for rhino mocks. Disclaimer: I haven't tried autofixture yet.