Register singleton that implements two interfaces - structuremap

What is the correct way to configure an object in structuremap that implements two interface but is a singleton.
For example class Main implements both iMainFrmService and iActiveJobService.
Here is what I've tried, but I'm not sure if it's correct.
ObjectFactory.Initialize(pExpression=>
{
pExpression.ForSingletonOf<iMainFrmService>().Use<Main>();
pExpression.ForSingletonOf<iActiveJobService>().Use<Main>();
});

As mentioned in the answer linked to from the comment above, x.Forward< , >() does give the singleton for both the interfaces.
Please check out this dotnetfiddle for a working sample. Here is snippet that is posted there:
using System;
using StructureMap;
namespace StructureMapSingleton {
public class Program {
public static void Main(string [] args) {
Bootstrapper.Initialize();
var mainService = Bootstrapper.GetInstance<IMainService>();
mainService.MainMethod();
var secondaryService = Bootstrapper.GetInstance<ISecondaryService>();
secondaryService.SecondMethod();
Console.ReadLine();
}
}
public interface IMainService {
void MainMethod();
}
public interface ISecondaryService {
void SecondMethod();
}
public class MainService : IMainService, ISecondaryService {
private int _invokeCount;
public void MainMethod() {
this._invokeCount++;
Console.WriteLine("In MainService: MainMethod ({0})", this._invokeCount);
}
public void SecondMethod() {
this._invokeCount++;
Console.WriteLine("In MainService: SecondMethod ({0})", this._invokeCount);
}
}
public class Bootstrapper {
private static Container _container;
public static void Initialize() {
_container = new Container(x => {
x.For<IMainService>().Singleton().Use<MainService>();
//x.For<ISecondaryService>().Singleton().Use<MainService>();
x.Forward<IMainService, ISecondaryService>();
});
}
public static T GetInstance<T>() {
return _container.GetInstance<T>();
}
}
}

Related

Dagger generated code compilation failed when using #Singleton annotation

I am using Dagger - 2.6 and i have the following classes.
public class Trigger {
public static JSONObject triggerLambda(JSONObject jsonObject) {
DataTransformerComponent daggerDataTransformerComponent = DaggerDataTransformerComponent.create();
return daggerDataTransformerComponent.getHandler().handle(jsonObject);
}
}
Data Handler class:
public class DataHandler {
private static final Logger LOGGER = Logger.getLogger(DataHandler.class.getName());
private A a;
#Inject
public DataHandler(A a) {
this.a = a;
}
public JSONObject handle(JSONObject input) {
LOGGER.info("Json input received - " + input.toString());
return a.executeTransformation(input);
}
}
And a dependency:
public class A {
#Inject
public A() {
}
public JSONObject executeTransformation(JSONObject jsonObject) {
System.out.println("a");
return null;
}
}
My component class looks like:
#Component
public interface DataTransformerComponent {
DataHandler getHandler();
}
When i compile the above code it runs absolutely fine.
Now i want to make my A dependency #Singleton.
So i change my dependency class and component class as follows:
#Singleton
#Component
public interface DataTransformerComponent {
DataHandler getHandler();
}
Dependency class:
#Singleton
public class A {
#Inject
public A() {
}
public JSONObject executeTransformation(JSONObject jsonObject) {
System.out.println("a");
return null;
}
}
But now the generated component shows compilation errors saying:
A_Factory not found and it fails in the initialize() method.
DaggerDataTransformerComponent :
#Generated(
value = "dagger.internal.codegen.ComponentProcessor",
comments = "https://google.github.io/dagger"
)
public final class DaggerDataTransformerComponent implements DataTransformerComponent {
private Provider<A> aProvider;
private Provider<DataHandler> dataHandlerProvider;
private DaggerDataTransformerComponent(Builder builder) {
assert builder != null;
initialize(builder);
}
public static Builder builder() {
return new Builder();
}
public static DataTransformerComponent create() {
return builder().build();
}
#SuppressWarnings("unchecked")
private void initialize(final Builder builder) {
this.aProvider = DoubleCheck.provider(A_Factory.create());
this.dataHandlerProvider = DataHandler_Factory.create(aProvider);
}
#Override
public DataHandler getHandler() {
return dataHandlerProvider.get();
}
public static final class Builder {
private Builder() {}
public DataTransformerComponent build() {
return new DaggerDataTransformerComponent(this);
}
}
}
I am unable to figure out why it does not create _factory class when i use #Singleton annotation.?.
Just use regular JavaScript + node.js, its a lot simpler

StructureMap - DI - Multiple Concrete Implementation

I have referred multiple threads for solution but those did not help :( Any help to provide solution in terms of code on below problem is appreciated
class Program
{
static void Main(string[] args)
{
//StructureMapConfiguration();
var registry = new Registry();
registry.IncludeRegistry<DependencyRegistry>();
var container = new Container(registry);
var depend = container.GetInstance<ITest>();
var controller1 = new Controller1(depend);
controller1.M1();
var controller2 = new Controller2(depend);
controller1.M1();
Console.Read();
}
}
public interface ITest
{
void Method();
}
public class A : ITest
{
public void Method()
{
Console.WriteLine("A");
}
}
public class B : ITest
{
public void Method()
{
Console.WriteLine("B");
}
}
public class C : ITest
{
public void Method()
{
Console.WriteLine("C");
}
}
public interface IController
{
void M1();
}
public class Controller1 : IController
{
private ITest _test;
public Controller1()
{
}
public Controller1(ITest test)
{
_test = test;
}
public void M1()
{
_test.Method();
}
}
public class Controller2 : IController
{
private ITest _test;
public Controller2(ITest test)
{
_test = test;
}
public void M1()
{
_test.Method();
}
}
public class DependencyRegistry : Registry
{
public DependencyRegistry()
{
For<ITest>().Use<A>().Named("A");
For<ITest>().Use<B>().Named("B");
For<ITest>().Use<C>().Named("C");
For<IController>().Add<Controller1>().Ctor<ITest>().Is(i => i.GetInstance<ITest>("A"));
For<IController>().Add<Controller2>().Ctor<ITest>().Is(i => i.GetInstance<ITest>("B"));
Scan(x =>
{
x.AssembliesFromApplicationBaseDirectory();
x.AddAllTypesOf<ITest>().NameBy(type => type.Name);
x.WithDefaultConventions();
});
}
}
}
Actual Result:
Everytime I am getting instance of class C for Controller1 and Controller2
Expected Result:
For Controller1, I need instance of class A and for Controller2, I need instance of class B
Thanks in advance

conditional DI with the help of config file

How can we achieve conditional Dependency Injection with the help of Unity Application block config file ? Below is my piece of code.
namespace DependencyInjection
{
//UI
class Program
{
static void Main(string[] args)
{
IUnityContainer objContainer = new UnityContainer();
objContainer.LoadConfiguration(); //loads from app
Customer obj = objContainer.Resolve<Customer>();
obj.CustomerName = "test1";
obj.Add();
}
}
//ML
public class Customer
{
private IDAL Odal;
public string CustomerName { get; set; }
public Customer(IDAL iobj)
{
Odal = iobj;
}
public void Add()
{
Odal.Add();
}
}
//DAL
public interface IDAL
{
void Add();
}
public class SQLServerDAL:IDAL
{
public void Add()
{
Console.WriteLine("SQL Server inserted");
Console.ReadLine();
}
}
public class OracleDAL:IDAL
{
public void Add()
{
Console.WriteLine("Oracle inserted");
Console.ReadLine();
}
}
}
And my config file is like below:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="DependencyInjection.IDAL, DependencyInjection"
mapTo="DependencyInjection.SQLServerDAL,DependencyInjection"/>
</container>
</unity>
How can I achieve the following :
If(somecondition=true)
Customer object should resolve to SQLServerDal
Else
Customer object should resolve to OracleDal
Is it possible ? If yes, how ?

Autofac. How to get caller class Type?

Suppose we have two classes with same constructor Injectable dependency:
public class FirstClass
{
public FirstClass(ISomeDependency someDependency)
{ }
}
public class SecondClass
{
public SecondClass(ISomeDependency someDependency)
{ }
}
Now we have a registration for ISomeDependency:
builder.Register(x =>
{
string key = GetKeyFromCurrentHttpRequest();
// if "Caller" is "FirstClass" return new Dependency(key);
// else return new Dependency("defaultKey");
}).As<ISomeDependency>();
Note: This is a simplified use case. The real scenario is much more complicated.
1. How to get "Caller" type which tryies to resolve ISomeDependency?
2. Is there a better way design for such situations?
You can use delegate factories do achieve your goal. The only drawback is the FirstClass and SecondClass cannot use ISomeDependency as parameter.
You can try this code in a console application (just add Autofac dependency).
using System;
using Autofac;
namespace test
{
class MainClass
{
public static void Main(string[] args)
{
ContainerBuilder builder = new ContainerBuilder ();
builder.RegisterType<SomeDependency>().As<ISomeDependency>();
builder.RegisterType<FirstClass>();
builder.RegisterType<SecondClass>();
var container = builder.Build();
var dummy = container.Resolve<FirstClass>();
var dummy2 = container.Resolve<SecondClass>();
}
public interface ISomeDependency
{
}
public class SomeDependency : ISomeDependency
{
public delegate ISomeDependency Factory(string value);
private readonly string _value;
public SomeDependency(string value)
{
_value = value;
Console.WriteLine("Value = " + _value);
}
}
public class FirstClass
{
private ISomeDependency _dependency;
public FirstClass(SomeDependency.Factory factory)
{
_dependency = factory.Invoke("my value");
}
}
public class SecondClass
{
private ISomeDependency _dependency;
public SecondClass(SomeDependency.Factory factory)
{
_dependency = factory.Invoke("my value 2");
}
}
}
}

Implementation-less typed factory issues

Take this simple example:
class Program
{
static void Main(string[] args)
{
var windsorContainer = new WindsorContainer();
windsorContainer.Install(new WindsorInstaller());
var editor = windsorContainer.Resolve<IEditor>();
editor.DoSomething();
Console.ReadKey();
}
}
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<ISomeOtherDependency>().ImplementedBy<SomeOtherDependency>());
container.Register(Component.For<IReviewingService>().ImplementedBy<ReviewingService>());
container.Register(Component.For<IEditor>().ImplementedBy<Editor>());
container.Register(Component.For<Func<IReviewingServiceFactory>>().AsFactory());
}
}
public interface IEditor
{
void DoSomething();
}
public class Editor : IEditor
{
private readonly Func<IReviewingServiceFactory> _reviewingService;
public Editor(Func<IReviewingServiceFactory> reviewingService)
{
_reviewingService = reviewingService;
}
public void DoSomething()
{
var rs = _reviewingService();
var reviews = new List<string> {"Review #1", "Review #2"};
var reviewingService = rs.Create(reviews);
reviewingService.Review();
}
}
public interface IReviewingServiceFactory
{
IReviewingService Create(IList<string> reviews);
}
public interface IReviewingService
{
void Review();
}
public class ReviewingService : IReviewingService
{
private readonly IList<string> _reviews;
private readonly ISomeOtherDependency _someOtherDependency;
public ReviewingService(IList<string> reviews, ISomeOtherDependency someOtherDependency)
{
_reviews = reviews;
_someOtherDependency = someOtherDependency;
}
public void Review()
{
Console.WriteLine("Reviewing...");
}
}
public interface ISomeOtherDependency
{
}
public class SomeOtherDependency : ISomeOtherDependency
{
}
With this example I would expect the console to output "Reviewing...". However, Windsor throws exceptions:
No component for supporting the service CastleWindsorTypedFactor.IReviewingServiceFactory was found
What is wrong with my Windsor installer?
You registered Func<IReviewingServiceFactory> instead of IReviewingServiceFactory... try replacing
container.Register(Component.For<Func<IReviewingServiceFactory>>().AsFactory());
with
container.Register(Component.For<IReviewingServiceFactory>().AsFactory());
and adapt the code accordingly - then it should work.
Oh, and another thing - you registered your IReviewingService without specifying a lifestyle, which will default to SINGLETON. That is most likely not what you want, because then your reviews argument will only be passed to the instance when is gets created, which only happens the first time the factory is called...! Additional calls to the factory will return the singleton instance.
Therefore: Change the lifestyle of IReviewingService to transient, AND create an appropriate release method signature on the factory interface (e.g. void Destroy(IReviewingService service)).

Resources