Autofac. How to get caller class Type? - dependency-injection

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");
}
}
}
}

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

typemock threw InvalidCast exception

I have following code snipped and I tried to test it using typemock but got InvalidCast exception. ISomeClass is just an interface and SomeClass implements that interface. UseOfSomeClass is another class which uses SomeClass and its constructor takes SomeClass as parameter. I need to test UseOfSomeClass. How do I inject a typemock fake object into a class constructor?
public interface ISomeClass
{
void DoSomething();
}
public class SomeClass : ISomeClass
{
public void DoSomething()
{
Console.WriteLine("Do something!");
}
}
public class UseOfSomeClass
{
public SomeClass SomeClassProperty { get; set; }
public bool IsChecked { get; set; }
public UseOfSomeClass(SomeClass someClass)
{
SomeClassProperty = someClass;
}
public void MyMethod()
{
SomeClassProperty.DoSomething();
IsChecked = true;
}
}
Then test:
[TestClass]
public class UseOfSomeClassTest
{
[TestMethod]
public void TestMethod1()
{
var fakeSomeClass = Isolate.Fake.Instance<ISomeClass>();
var use = new UseOfSomeClass((SomeClass)fakeSomeClass);
use.MyMethod();
Assert.IsTrue(use.IsChecked);
}
}
Thanks!
Typemock Isolator allows you to mock concrete classes, so there's no need to fake ISomeClass in your test case. You can just fake SomeClass and send it as a parameter to the ctor.
[TestMethod, Isolated]
public void TestMethod1()
{
var fakeSomeClass = Isolate.Fake.Instance<SomeClass>();
var use = new UseOfSomeClass(fakeSomeClass);
use.MyMethod();
Assert.IsTrue(use.IsChecked);
}

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)).

StructureMap Question

This is the equivalent of what I'm trying to create with StructureMap:
new ChangePasswordWithNotificationAndLoggingService(
new ChangePasswordService(
new ActiveDirectoryRepository(new ActiveDirectoryCredentials()),
new TokenRepository("")),
new EmailNotificationService(new PasswordChangedNotification(new UserAccount())),
new LoggingService());
This is what I have right now:
ForRequestedType<IChangePasswordService>()
.TheDefault.Is.ConstructedBy(() =>
new ChangePasswordService(DependencyRegistrar.Resolve<IActiveDirectoryRepository>(),
DependencyRegistrar.Resolve<ITokenRepository>()))
.EnrichWith<IChangePasswordService>(x =>
new ChangePasswordWithNotificationAndLoggingService(x,
DependencyRegistrar.Resolve<INotificationService>(),
DependencyRegistrar.Resolve<ILoggingService>()));
I need to pass the UserAccount to the INotificationService...can't figure it out.
I've tried this:
DependencyRegistrar.With(new UserAccount { Username = "test" });
No luck...UserAccount always turns out null. I don't have to do it all with StructureMap, I'm open to any suggestions.
This is what I currently have working:
public static IChangePasswordService ChangePasswordService(UserAccount userAccount)
{
return new ChangePasswordWithNotificationService(
new ChangePasswordService(ActiveDirectoryRepository(), TokenRepository()),
new EmailNotificationService(new PasswordChangedNotification(userAccount)));
}
Have you tried just using AutoWiring? These are all concrete classes with simple construction so StructureMap can figure out what you need.
For<IChangePasswordService>().Use<ChangePasswordService>();
Looking at your construction I think that this simple configuration might just work.
Edit
Regarding the comments.
You should use the With(T instance) method to have the container construct your IChangePasswordService using the given userAccount.
var userAccount = new UserAccount("derans");
var changePasswordService = container.With(userAccount).GetInstance<IChangePasswordService>();
Why not encapsulate the creation of the change password service into a factory - the factory is then an implemented as StructureMap factory that use a UserAccount passed in and the 'ObjectFactory' to create instances of the IIChangePasswordService as required?
I have demo'ed it below:
namespace SMTest
{
class Program
{
static void Main(string[] args)
{
// bootstrapper...
ObjectFactory.Configure(x => x.AddRegistry(new TestRegistry()));
// create factory for use later (IoC manages this)...
var changePasswordServiceFactory = ObjectFactory.GetInstance<IChangePasswordServiceFactory>();
var daveAccount = new UserAccount("Dave Cox");
var steveAccount = new UserAccount("Steve Jones");
var passwordService1 = changePasswordServiceFactory.CreateForUserAccount(daveAccount);
var passwordService2 = changePasswordServiceFactory.CreateForUserAccount(steveAccount);
}
}
public class TestRegistry : Registry
{
public TestRegistry()
{
Scan(x =>
{
x.TheCallingAssembly();
x.AssemblyContainingType(typeof(IChangePasswordService));
x.AssemblyContainingType(typeof(IActiveDirectoryRepository));
x.AssemblyContainingType(typeof(IActiveDirectoryCredentials));
x.AssemblyContainingType(typeof(ITokenRepository));
x.AssemblyContainingType(typeof(INotification));
x.AssemblyContainingType(typeof(INotificationService));
x.AssemblyContainingType(typeof(ILoggingService));
ForRequestedType<ILoggingService>().TheDefault.Is.OfConcreteType<MyLogger>();
ForRequestedType<IActiveDirectoryRepository>().TheDefault.Is.OfConcreteType<MyAdRepository>();
ForRequestedType<IActiveDirectoryCredentials>().TheDefault.Is.OfConcreteType<MyAdCredentials>();
ForRequestedType<ITokenRepository>().TheDefault.Is.OfConcreteType<MyTokenRepository>();
ForRequestedType<IChangePasswordService>().TheDefault.Is.OfConcreteType<ChangePasswordService>();
ForRequestedType<IChangePasswordServiceFactory>().CacheBy(InstanceScope.Singleton).TheDefault.Is.OfConcreteType<StructureMapChangePasswordServiceFactory>();
ForRequestedType<INotification>().TheDefault.Is.OfConcreteType<MyPasswordChangedNotification>();
ForRequestedType<INotificationService>().TheDefault.Is.OfConcreteType<MyEmailNotificationService>();
});
}
}
public interface ILoggingService
{
}
public class MyLogger : ILoggingService
{
}
public class UserAccount
{
public string Name { get; private set; }
public UserAccount(string name)
{
Name = name;
}
}
public interface INotification
{
}
public class MyPasswordChangedNotification : INotification
{
private readonly UserAccount _account;
private readonly ILoggingService _logger;
public MyPasswordChangedNotification(UserAccount account, ILoggingService logger)
{
_account = account;
_logger = logger;
}
}
public interface INotificationService
{
}
public class MyEmailNotificationService : INotificationService
{
private readonly INotification _notification;
private readonly ILoggingService _logger;
public MyEmailNotificationService(INotification notification, ILoggingService logger)
{
_notification = notification;
_logger = logger;
}
}
public interface ITokenRepository
{
}
public class MyTokenRepository : ITokenRepository
{
}
public interface IActiveDirectoryRepository
{
}
public interface IActiveDirectoryCredentials
{
}
public class MyAdCredentials : IActiveDirectoryCredentials
{
}
public class MyAdRepository : IActiveDirectoryRepository
{
private readonly IActiveDirectoryCredentials _credentials;
public MyAdRepository(IActiveDirectoryCredentials credentials)
{
_credentials = credentials;
}
}
public interface IChangePasswordService
{
}
public class ChangePasswordService : IChangePasswordService
{
private readonly IActiveDirectoryRepository _adRepository;
private readonly ITokenRepository _tokenRepository;
private readonly INotificationService _notificationService;
public ChangePasswordService(IActiveDirectoryRepository adRepository, ITokenRepository tokenRepository, INotificationService notificationService)
{
_adRepository = adRepository;
_tokenRepository = tokenRepository;
_notificationService = notificationService;
}
}
public interface IChangePasswordServiceFactory
{
IChangePasswordService CreateForUserAccount(UserAccount account);
}
public class StructureMapChangePasswordServiceFactory : IChangePasswordServiceFactory
{
public IChangePasswordService CreateForUserAccount(UserAccount account)
{
return ObjectFactory.With(account).GetInstance < IChangePasswordService>();
}
}
}

Depedency injection: injecting partially-initialized objects

This question is about Unity Container but I guess it is applicable to any dependency container.
I have two classes with circular dependencies:
class FirstClass
{
[Dependency]
public SecondClass Second { get; set; }
}
class SecondClass
{
public readonly FirstClass First;
public SecondClass(FirstClass first)
{
First = first;
}
}
Technically it's possible to instantiate and correctly inject dependencies for both of them if treat them as singletons:
var firstObj = new FirstClass();
var secondObj = new SecondClass(firstObj);
firstObj.Second = secondObj;
When I try to do the same with Unity, I get StackOverflowException:
var container = new UnityContainer();
container.RegisterType<FirstClass>(new ContainerControlledLifetimeManager());
container.RegisterType<SecondClass>(new ContainerControlledLifetimeManager());
var first = container.Resolve<FirstClass>(); // StackOverflowException here!
var second = container.Resolve<SecondClass>(); // StackOverflowException here too!
I understand that Unity tries to protect me from using partially initialized objects but I want to have this protection as an option, not an obligation.
Question: is current behavior disabable?
I think you cannot use circular dependencies with unity at all.
See:
http://msdn.microsoft.com/en-us/library/cc440934.aspx
One way round this would be to use lazy loading for the dependencies on one of the classes:
[TestFixture]
public class CircularUnityTest
{
IUnityContainer container;
[SetUp]
public void SetUp()
{
container = new UnityContainer();
container.RegisterType(typeof(ILazy<>), typeof(Lazy<>));
container.RegisterType<FirstClass>(new ContainerControlledLifetimeManager());
container.RegisterType<SecondClass>(new ContainerControlledLifetimeManager());
}
[Test]
public void CanResolveFirstClass()
{
var first = container.Resolve<FirstClass>();
Assert.IsNotNull(first);
}
[Test]
public void CanResolveSecondClass()
{
var second = container.Resolve<SecondClass>();
Assert.IsNotNull(second);
}
[Test]
public void CanGetFirstFromSecond()
{
var second = container.Resolve<SecondClass>();
Assert.IsNotNull(second.First);
}
}
class FirstClass
{
[Dependency]
public SecondClass Second { get; set; }
}
class SecondClass
{
private readonly ILazy<FirstClass> lazyFirst;
public FirstClass First { get { return lazyFirst.Resolve(); } }
public SecondClass(ILazy<FirstClass> lazyFirst)
{
this.lazyFirst = lazyFirst;
}
}
public interface ILazy<T>
{
T Resolve();
}
public class Lazy<T> : ILazy<T>
{
IUnityContainer container;
public Lazy(IUnityContainer container)
{
this.container = container;
}
public T Resolve()
{
return container.Resolve<T>();
}
}
you can use RegisterInstance instead of RegisterType to achieve your goal. It will behave just like singleton - will use the same instance every time Resolve is invoked. Take a look at this example:
class FirstClass
{
[Dependency]
public SecondClass Second { get; set; }
}
class SecondClass
{
public readonly FirstClass First;
public SecondClass(FirstClass first)
{
First = first;
}
}
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
var firstObj = new FirstClass();
var secondObj = new SecondClass(firstObj);
firstObj.Second = secondObj;
// Register instance instead of type!!!
container.RegisterInstance<FirstClass>(firstObj);
container.RegisterType<SecondClass>();
var first = container.Resolve<FirstClass>();
var second = container.Resolve<SecondClass>();
}
}
Cheers,
Pavel

Resources