How to create a wrapper around DryIoC container.OpenScope()? - scope

I created a wrapper around DryIoC container which is just a class that delegates tasks to DryIoC methods ( for example, myContainer.Register<T>() will call dryIoC.Register<T>() ). the goal is just to hide the real implementation behind my interface so I can switch to another DI container if I wanted to.
All works fine, but I faced a problem today when I tried to work with Scopes likes in this example code taken from here
// example using DryIoC
var container = new Container();
container.Register<B>();
using (var scope = container.OpenScope())
{
var a = new A();
scope.UseInstance(a); // Scoped
scope.Resolve<B>(); // will inject `a`
}
var anotherA = new A();
container.UseInstance(anotherA); // Singleton
container.Resolve<B>(); // will inject `anotherA`
my naive wrapper implementation was to create another constructor that accepts an instance of DryIoC container and do it like this :
// My Wrapper class
public Infrastructure.IMyContainer OpenScope()
{
return new MyContainer(dryIoC.OpenScope());
}
my understanding is that dryIoC.OpenScope() returns a new instance of the container, so all I had to do is save this instance internally and use it to resolve my classes. but that implementation didn't work for me, here my unit test :
[Test]
public void OpenScope_Creates_A_Scoped_Container()
{
var _container = new MyContainer();
_container.Register<IMyInterface, MyImpl>();
_container.Register<MyDependingClass>();
MyDependingClass cls1 = null;
MyDependingClass cls2 = null;
var dep = new MyImpl();
using (var scope = _container.OpenScope())
{
scope.UseInstance(dep);
cls1 = scope.Resolve<MyDependingClass>(); // this should inject 'dep' instance created in the line before the creation of the scope
}
cls2 = _container.Resolve<MyDependingClass>(); // this should inject another instance.
cls1.Dep.ShouldBeSameAs(dep); // cls1 was resolved in the scope, so it should get 'dep' instance
cls1.Dep.ShouldNotBeSameAs(cls2.Dep); // cls2.Dep should be different
}
// stub classes/interfaces
class MyDependingClass
{
public MyDependingClass(IMyInterface dep)
{
Dep = dep;
}
public IMyInterface Dep { get; }
}
class MyImpl : IMyInterface { }
but this test fails at cls1.Dep.ShouldBeSameAs(dep); telling me that the two instances of IMyInterface was different !!!
Am I missing something ??

Related

How to use class functions in another class?

How can i use class instance in another class like a pointer in C++ to class instance functions?
Example:
class A {
constructor()
{
this.block = [];
}
method()
{
return this.blocks.length;
}
}
another class:
class B {
constructor(instance)
{
this.instance = instance;
}
method()
{
this.instance.method(); // here i'm getting cannot get length of undefined
}
}
If i'm trying to to like that i'm getting problems to call it
You can try this. Here, when creating B class's instance I give into it an A class's instance as argument. Then inside B we can call A instance's methods, and access its properties.
Also, as #ViaTech posted you can use static methods to access them without needing to initialize an object of the class. That is what static methods is. Refer Static Methods
class B {
constructor(instance)
{
this.instance = instance;
}
method()
{
this.instance.method();
}
}
class A {
constructor()
{
}
method()
{
console.log("A's method");
}
}
var a = new A();
var b = new B(a);
b.method(); // A's method
You can easily do this in JS by calling a static method like so:
class A {
static write(){ //static method
console.log("Called write from A");
}
}
class B {
doIt(){
A.write();
}
}
let b = new B();
b.doIt();
Option 2, you instantiate the class in the constructor of the other like so:
class A {
write(){
console.log("Non-static write() called from class A");
}
}
class B {
constructor() {
this.a = new A();
}
doIt(){
this.a.write();
}
}
let b = new B();
b.doIt();
There are a few ways:
I accidentally switched between PHP and Javascript, but the principles are the same for both)
Use static functions:
Normally, you have a this in the class. Say you have this code:
class Car {
let color;
public function setColor(newColor){ this.color = newColor;}
}
let car = new Car();
car->setColor('green')`
The setColor function's this refers to that car. You can make let anotherCar = new Car(), then when you do anotherCar->setColor('red') you only change that car, not the first one. Simplistic: You can create multiple instances.
If you do not need that, but need the class once, you can make it static. A simple way to explain would be "you have a collection of seperate functions, just put into a wrapping class (which doesn't do a lot really)". For instance, you might have some sanatizing methods:
class Sanitize {
static function makeHtmlSave(input){
return doYourMagicHere(input);
}
static function removeXssCode(input){
return doMoreMagicHere(input);
}
}
This way, you can reuse it multiple times. If you want to use it, you do Sanitize::makeHtmlSave(someCode) where you need it. There isn't a Sanitize thing, it's just a wrapper to access the frunctions inside it.
Use extend:
You can extend a class. Say you have a generic class Vehicle, which has some properties (eg a motor, numberWeels, color) and you can extend that with more specific classes:
class Vehicle {
let color;
public function setColor(newColor){ this.color = newColor}
}
class Car extends Vehicle {
let hasAirco = false;
public function hasAirco(newValue){ this.hasAirco = newValue};
}
If you do let car = new Car(), you get a Car object, that extends/enlarges/complements the Vehicle class, so you can use both its (public) functions. Internally, Car can use the functions of Vehicle too.
Just pass it
class One {
// some stuff
}
class Two{
let otherObject;
construct(givenObject){
this.otherObject = givenObject;
}
}
You can now do this let a = new One(); let b = new Two(a);. You can not use the functions of One inside Two, but you can still use a->doSomething(). This solution feels like the easiest, but it almost never is. Classes/objects are tricky stuff, but I've rarely uses this solutions. There are use cases, but often it's a bad smell indicator.

How to create namespace hierarchy in node.js addon?

I'm creating a node.js addon, which has bunch of classes. I want to organize them in a hierarchical namespace. If I were doing this in Javascript it would look like this
var com = function() {};
com.example = function() {};
com.example.Person = function () {};
var p = new com.example.Person();
I'm using Nan to write my node.js binding. To achieve the above result I've written code as follows:
com.h
namespace addon {
void init(Local<Object> exports);
}
com.cpp
void addon::init(Local<Object> exports)
{
addon::Example::Init(exports);
}
NODE_MODULE(com, com::init)
example.h
namespace addon {
class Example : public Nan::ObjectWrap {
static void Init(v8::Local<v8::Object> exports);
}
}
example.cpp
void addon::Example::Init(v8::Local<v8::Object> exports) {
// Prepare constructor template
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("example").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
addon::Person::Init(tpl);
constructor.Reset(tpl->GetFunction());
}
person.h
namespace addon {
class Person : public Nan::ObjectWrap {
static void Init(v8::Local<v8::FunctionTemplate> exports);
}
}
person.cpp
void addon::Person::Init(v8::Local<v8::FunctionTemplate> nmspace) {
Nan::HandleScope scope;
// Prepare constructor template
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Person").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
// ...
constructor.Reset(tpl->GetFunction());
nmspace->Set(Nan::New("Person").ToLocalChecked(), tpl->GetFunction()); // XXXXXX
}
This code compiles and also successfully passes the tests when run. However I get a warning when the addon is loaded.
(node) v8::FunctionTemplate::Set() with non-primitive values is deprecated
(node) and will stop working in the next major release.
It prints a stack trace. The top of this trace is at the line marked XXXXXX.
If this is not the recommended way to define a FunctionTemplate as a member of another FunctionTemplate, then what's the right way to achieve it? Any ideas?
I found an easy way to do this. It occured to me that I could achieve the same thing with the following Javascript code.
var com = {};
com.example = {};
com.example.Person = function () {};
var p = new com.example.Person();
So I found that it's totally unnecessary to define a ObjectWrap class for Example. Instead I defined it as a simple object
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::Handle<Object> example = v8::Object::New(isolate);
and then passed it to Person::Init() like this
void addon::Person::Init(v8::Local<v8::Object> nmspace) {
// ...
nmspace->Set(Nan::New("Person").ToLocalChecked(), tpl->GetFunction());
}
The resulting code works without any warnings or errors.

Kotlin thread safe native lazy singleton with parameter

In java we can write thead-safe singletons using double Checked Locking & volatile:
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance(String arg) {
Singleton localInstance = instance;
if (localInstance == null) {
synchronized (Singleton.class) {
localInstance = instance;
if (localInstance == null) {
instance = localInstance = new Singleton(arg);
}
}
}
return localInstance;
}
}
How we can write it in kotlin?
About object
object A {
object B {}
object C {}
init {
C.hashCode()
}
}
I used kotlin decompiler to get that
public final class A {
public static final A INSTANCE;
private A() {
INSTANCE = (A)this;
A.C.INSTANCE.hashCode();
}
static {
new A();
}
public static final class B {
public static final A.B INSTANCE;
private B() {
INSTANCE = (A.B)this;
}
static {
new A.B();
}
}
public static final class C {
public static final A.C INSTANCE;
private C() {
INSTANCE = (A.C)this;
}
static {
new A.C();
}
}
}
All of object have constructor invoke in static block. Based on it, we can think that it's not lazy.
Сlose to the right answer.
class Singleton {
companion object {
val instance: Singleton by lazy(LazyThreadSafetyMode.PUBLICATION) { Singleton() }
}
}
Decompiled:
public static final class Companion {
// $FF: synthetic field
private static final KProperty[] $$delegatedProperties = new KProperty[]{(KProperty)Reflection.property1(new PropertyReference1Impl(Reflection.getOrCreateKotlinClass(Singleton.Companion.class), "instance", "getInstance()Lru/example/project/tech/Singleton;"))};
#NotNull
public final Singleton getInstance() {
Lazy var1 = Singleton.instance$delegate;
KProperty var3 = $$delegatedProperties[0];
return (Singleton)var1.getValue();
}
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
I hope Kotlin developers will make non reflection implementation in future...
Kotlin has an equivalent of your Java code, but more safe. Your double lock check is not recommended even for Java. In Java you should use an inner class on the static which is also explained in Initialization-on-demand holder idiom.
But that's Java. In Kotlin, simply use an object (and optionally a lazy delegate):
object Singletons {
val something: OfMyType by lazy() { ... }
val somethingLazyButLessSo: OtherType = OtherType()
val moreLazies: FancyType by lazy() { ... }
}
You can then access any member variable:
// Singletons is lazy instantiated now, then something is lazy instantiated after.
val thing = Singletons.something // This is Doubly Lazy!
// this one is already loaded due to previous line
val eager = Singletons.somethingLazyButLessSo
// and Singletons.moreLazies isn't loaded yet until first access...
Kotlin intentionally avoids the confusion people have with singletons in Java. And avoids the "wrong versions" of this pattern -- of which there are many. It instead provides the simpler and the safest form of singletons.
Given the use of lazy(), if you have other members each would individually be lazy. And since they are initialized in the lambda passed to lazy() you can do things that you were asking about for about customizing the constructor, and for each member property.
As a result you have lazy loading of Singletons object (on first access of instance), and then lazier loading of something (on first access of member), and complete flexibility in object construction.
See also:
lazy() function
Lazy thread safe mode options
Object declarations
As a side note, look at object registry type libraries for Kotlin that are similar to dependency injection, giving you singletons with injection options:
Injekt - I'm the author
Kodein - Very similar and good
Object declaration is exactly for this purpose:
object Singleton {
//singleton members
}
It is lazy and thread-safe, it initializes upon first call, much as Java's static initializers.
You can declare an object at top level or inside a class or another object.
For more info about working with objects from Java, please refer to this answer.
As to the parameter, if you want to achieve exactly the same semantics (first call to getInstance takes its argument to initialize the singleton, following calls just return the instance, dropping the arguments), I would suggest this construct:
private object SingletonInit { //invisible outside the file
lateinit var arg0: String
}
object Singleton {
val arg0: String = SingletonInit.arg0
}
fun Singleton(arg0: String): Singleton { //mimic a constructor, if you want
synchronized(SingletonInit) {
SingletonInit.arg0 = arg0
return Singleton
}
}
The main flaw of this solution is that it requires the singleton to be defined in a separate file to hide the object SingletonInit, and you cannot reference Singleton directly until it's initialized.
Also, see a similar question about providing arguments to a singleton.
I recently wrote an article on that topic.
TL;DR Here's the solution I came up to:
1) Create a SingletonHolder class. You only have to write it once:
open class SingletonHolder<out T, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator
#Volatile private var instance: T? = null
fun getInstance(arg: A): T {
val i = instance
if (i != null) {
return i
}
return synchronized(this) {
val i2 = instance
if (i2 != null) {
i2
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
}
2) Use it like this in your singletons:
class MySingleton private constructor(arg: ArgumentType) {
init {
// Init using argument
}
companion object : SingletonHolder<MySingleton, ArgumentType>(::MySingleton)
}
The singleton initialization will be lazy and thread-safe.

Resolving Dependency by user parameter

I often need to use some class which itself have to load some dependency to work.
However, my component can have more than one concrete dependency implementation and it will choose one, rather than another one on some object parameter basis.
The real problem is that the object parameter is always unknown when application start up, so I'm not able in this moment to register any dependency, neither to resolve them.
Instead, for instance, when I need to use some class which itself needs to load some dependency I know the object parameter used by concreteBuilder in order to return me the appropriate implementation:
interface ISample { }
class ParamForBuildSomeISampleImplementation
{
// this instance cannot be create by my startUpApplication - Container - Resolver.
// Instead, all time dependency is required (buttonClick, pageLoad and so on), this class can be instantiated.
}
class Sample1 : ISample
{
// some implementation
}
class Sample2 : ISample
{
// some other implementation
}
class MyISampleFactory
{
// Build ISample
public ISample Build(ParamForBuilderISample obj)
{
// if obj.someProperty == ".." return new Sample1();
// else if obj.someProperty == "--" return new Sample2();
// else if ...
}
}
class NeedsDependency
{
ISample _someSample;
public NeedsDependency(ISample someSample)
{
_someSample = someSample;
}
}
// *** Controllor - ApplicationStartup - other ***
// Here I have not idea how to build ISample dependency
## EDIT
// *** button click event handler ***
// Ok, here I know how to create ParamForBuilderISample,
// hence I can call MyISampleFactory, then, I can Use NeedDependency class:
ParamForBuilderISample obj = new ...
obj.SomeProperty = ...
obj.otherSomeProperty = ...
ISample sample = MyISampleFactory.Build(obj);
NeedDependency nd = new NeedDependency(sample);
// perfect, now my buttonClick can execute all what it wants
nd.DoSomething();
nd.DoOtherStuff();
Is my scenario suitable to Dependency Injection pattern? If true, I really have not idea how build my pattern.
Instead of using constructor injection for passing in this 'runtime dependency', you might be better of using method injection. This might even completely remove the need for having a factory:
private readonly ISample sample;
public MyController(ISample sample) {
this.sample = sample;
}
public string button_click_event_handler(object s, EventArgs e) {
ParamForBuilderISample obj = new ...
obj.SomeProperty = ...
obj.otherSomeProperty = ...
this.sample.DoSomething(obj);
}
You still need to switch somewhere, but instead of having a factory, you could implement a proxy for ISample:
public class SampleProxy : ISample
{
private readonly Sample1 sample1;
private readonly Sample2 sample2;
public SampleProxy(Sample1 sample1, Sample2 sample2) {
this.sample1 = sample1;
this.sample2 = sample2;
}
public void DoSomething(ParamForBuilderISample param) {
this.GetSampleFor(param).DoSomething(param);
}
private ISample GetSampleFor(ParamForBuilderISample param) {
// if obj.someProperty == ".." return this.sample1;
// else if obj.someProperty == "--" return this.sample2;
// else if ...
}
}
Your ParamForBuilderISample looks like a parameter object. Dependency injection doesn't remove the need to have method arguments. Data should still be passed on through methods.

How does one extend MEF to create objects based on a factory type provided as an attribute?

Consider the following existing classes which uses MEF to compose Consumer.
public interface IProducer
{
void Produce();
}
[Export(typeof(IProducer))]
public class Producer : IProducer
{
public Producer()
{
// perform some initialization
}
public void Produce()
{
// produce something
}
}
public class Consumer
{
[Import]
public IProducer Producer
{
get;
set;
}
[ImportingConstructor]
public Consumer(IProducer producer)
{
Producer = producer;
}
public void DoSomething()
{
// do something
Producer.Produce();
}
}
However, the creation of Producer has become complex enough that it can no longer be done within the constructor and the default behavior no longer suffices.
I'd like to introduce a factory and register it using a custom FactoryAttribute on the producer itself. This is what I have in mind:
[Export(typeof(IProducer))]
[Factory(typeof(ProducerFactory))]
public class Producer : IProducer
{
public Producer()
{
// perform some initialization
}
public void Produce()
{
// produce something
}
}
[Export]
public class ProducerFactory
{
public Producer Create()
{
// Perform complex initialization
return new Producer();
}
}
public class FactoryAttribute : Attribute
{
public Type ObjectType
{
get;
private set;
}
public FactoryAttribute(Type objectType)
{
ObjectType = objectType;
}
}
If I had to write the "new" code myself, it may very well look as follows. It would use the factory attribute, if it exists, to create a part, or default to the MEF to create it.
public object Create(Type partType, CompositionContainer container)
{
var attribute = (FactoryAttribute)partType.GetCustomAttributes(typeof (FactoryAttribute), true).FirstOrDefault();
if (attribute == null)
{
var result = container.GetExports(partType, null, null).First();
return result.Value;
}
else
{
var factoryExport = container.GetExports(attribute.ObjectType, null, null).First();
var factory = factoryExport.Value;
var method = factory.GetType().GetMethod("Create");
var result = method.Invoke(factory, new object[0]);
container.ComposeParts(result);
return result;
}
}
There are a number of articles how to implement a ExportProvider, including:
MEF + Object Factories using Export Provider
Dynamic Instantiation
However, the examples are not ideal when
The application has no dependencies or knowledge of Producer, only IProducer. It would not be able to register the factory when the CompositionContainer is created.
Producer is reused by several applications and a developer may mistakenly forget to register the factory when the CompositionContainer is created.
There are a large number of types that require custom factories and it may pose a maintenance nightmare to remember to register factories when the CompositionContainer is created.
I started to create a ExportProvider (assuming this would provide the means to implement construction using factory).
public class FactoryExportProvider : ExportProvider
{
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition,
AtomicComposition atomicComposition)
{
// What to do here?
}
}
However, I'm having trouble understanding how to tell MEF to use the factory objects defined in the FactoryAttribute, and use the default creation mechanism if no such attribute exists.
What is the correct manner to implement this? I'm using MEF 2 Preview 5 and .NET 4.
You can make use of a property export:
public class ProducerExporter
{
[Export]
public IProducer MyProducer
{
get
{
var producer = new Producer();
// complex initialization here
return producer;
}
}
}
Note that the term factory isn't really appropriate for your example, I would reserve that term for the case where the importer wants to create instances at will, possibly by providing one or more parameters. That could be done with a method export:
public class ProducerFactory
{
[Export(typeof(Func<Type1,Type2,IProducer>)]
public IProducer CreateProducer(Type1 arg1, Type2 arg2)
{
return new Producer(arg1, arg2);
}
}
On the import side, you would then import a Func<Type1,Type2,IProducer> that you can invoke at will to create new instances.

Resources