I'm trying to use autofac for dependency injection in my console app. I'm running into issues where autofac can't find constructors for certain interfaces/classes.
Here is my latest example:
IRepository:
public interface IRepository<Planetary>
{
IEnumerable<Planetary> Get();
}
IPlanetaryRepository:
public interface IPlanetaryRepository : IRepository<Planetary>
{
IQueryable<Planetary> GetPlanetary(SystemProbe user);
}
PlanetaryService:
public interface IPlanetaryService
{
Task<Planetary> Clone(Planetary source);
}
public sealed class PlanetaryService : IPlanetaryService
{
private IPlanetaryRepository Repo { get; }
public PlanetaryService(IPlanetaryRepository repo)
{
Repo = repo;
}
}
Scheduler:
public class Scheduler
{
private static IContainer Container { get; set; }
static void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<PlanetaryService>().As<PlanetaryService>();
builder.RegisterType<IPlanetaryRepository>().As<IPlanetaryRepository>();
Container = builder.Build();
GenerateSchedules();
}
public static void GenerateSchedules()
{
using (var scope = Container.BeginLifetimeScope())
{
var repo = scope.Resolve<PlanetaryService>(); <-- line where exception is thrown
}
}
}
No constructors on type 'IPlanetaryRepository' can be found with the
constructor finder
'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.
If I take out IPlanetaryRepository, I get this exception:
Cannot resolve parameter IPlanetaryRepository repo of constructor...
So I'm not really sure what to do. 'PlanetaryService' needs 'IPlanetaryRepository' as a parameter, but IPlanetaryRepository doesn't have a constructor.
Is there a way to rectify this?
You don'y have any classes that implement IPlanetaryRepository so it can't find the constructor.
Related
Is it possible to create a class under test with FakeItEasy, where all dependencies that are declared in the constructor are initialized automatically with fakes?
Imagine the class:
public class Inserting
{
public Inserting(
ITransactionService transactionService,
ISharedData sharedData)
{
TransactionService = transactionService;
SharedData = sharedData;
}
public ITransactionService TransactionService { get; }
public ISharedData SharedData { get; }
public void Enter()
{
TransactionService.StartTransaction();
}
}
Then I am creating all fake-objects in the test setup and construct my class under test with those fakes:
public class InsertingTest
{
private Inserting _inserting;
private ISharedData _fakeSharedData;
private ITransactionService _fakeTransactionService;
[SetUp]
public void SetUp()
{
_fakeTransactionService = A.Fake<ITransactionService>();
_fakeSharedData = A.Fake<ISharedData>();
_inserting = new Inserting(_fakeTransactionService, _fakeSharedData);
}
[Test]
public void TestEnter()
{
// Arrange
// Act
_inserting.Enter();
// Assert
A.CallTo(() => _fakeTransactionService.StartTransaction().MustHaveHappened();
}
}
But I saw in the Java-world, that when using Mockito and Dagger 2, you can do something like this:
public class PhoneDialer {
private Activity activity;
private PhoneCallListener phoneCallListener;
#Inject
public PhoneDialer(Activity activity, PhoneCallListener phoneCallListener) {
this.activity = activity;
this.phoneCallListener = phoneCallListener;
}
}
public class PhoneDialerTest {
#Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
#Mock
PhoneCallListener phoneCallListener;
#Mock
Activity activity;
#InjectMocks
PhoneDialer dialer;
#Test
public void test_dialer() throws Exception {
// Arrange
// Act
dialer.callNumber("abc");
// Assert
Mockito.verify(phoneCallListener, times(1)).startCall();
}
}
and the mocked classes are initialized automatically with fakes. Is there an equivalent procedure or function in C# with FakeItEasy?
I think you want something like
Automatically inject fakes in test fixture with FakeItEasy. You use [Fake] to mark fakes to inject and [UnderTest] to mark the production type to test.
We really should put this into the documentation.
Alternatively,
AutoFixture has an AutoFixture.AutoFakeItEasy module,
there's Autofac FakeItEasy integration, and also
Ninject FakeItEasy integration
I saw 'Automatically inject fakes in text fixture with FakeItEasy' and my initial reaction was surprise that it differed from my preconception, mainly because it needs 'intrusive' changes that attribute the test code... but perhaps that is an overreaction.
The FakeAttribute and UnderTestAttribute do force what is potentially a good structural constraint on your test (and system) design...
[FWLIW, before googling this, I had imagined the following:
containerBuilder.RegisterAsFakeCallingBaseType<SystemUnderTest>();
You can do something like this with Autofac's registration sources.
using Autofac;
using Autofac.Core;
using Autofac.Core.Activators.Delegate;
using Autofac.Core.Lifetime;
using Autofac.Core.Registration;
using FakeItEasy;
using Xunit;
public interface IDependOnSomething { }
public class IImplementThat : IDependOnSomething { }
public class CanIResolveIt
{
public CanIResolveIt(IDependOnSomething it)
{
}
}
public class FakeRegistrationSourceTest
{
[Fact]
public void BasicTest()
{
var container = new ContainerBuilder();
container.RegisterTypes<IImplementThat>().As<IDependOnSomething>();
container.RegisterSource(new FakeRegistrationSource<CanIResolveIt>());
var c = container.Build();
var theFake = c.Resolve<CanIResolveIt>();
Assert.NotNull(theFake);
}
}
public class FakeRegistrationSource<T> : IRegistrationSource
where T : class
{
public bool IsAdapterForIndividualComponents => false;
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var swt = service as IServiceWithType;
if (swt == null || !typeof(T).IsAssignableFrom(swt.ServiceType)) // TODO: is this the right way around?
{
return Enumerable.Empty<IComponentRegistration>();
}
var registration = new ComponentRegistration(
Guid.NewGuid(),
new DelegateActivator(swt.ServiceType, (context, #params) =>
{
List<object> v = new List<object>();
foreach (ParameterInfo p in typeof(T).GetConstructors().Single().GetParameters())
{
v.Add(context.Resolve(p.ParameterType));
}
return A.Fake<T>(that => that.CallsBaseMethods().WithArgumentsForConstructor(v));
}),
new CurrentScopeLifetime(),
InstanceSharing.None,
InstanceOwnership.OwnedByLifetimeScope,
new[] { service },
new Dictionary<string, object>());
return new IComponentRegistration[] { registration };
}
}
Main advantage of this approach is that it knows how to instantiate fake objects subclassing classes with constructor parameters, and inheriting their default behavior, when they have a single constructor (choosing intelligently from multiple constructors would be an obvious challenge that I'm not going to tackle...)
An obvious drawback is explicit registration every time you want something faked. AutoFake and so on offer ways to overcome that with faking of just about everything by default, which might well be what you want... and you can override it if not.]
Hi am working on console application which uses Dependency Injection pattern, i have created the interface like
public interface IRecurringTransactionPlanDataService : IService<RecurringTransactionPlan>
{
IQueryable<RecurringTransactionPlan> RecurringTransactionPlanData();
}
and the class implements as
public class RecurringTransactionPlanDataService : Service<RecurringTransactionPlan>, IRecurringTransactionPlanDataService
{
private readonly IRepositoryAsync<RecurringTransactionPlan> _repository;
public RecurringTransactionPlanDataService(IRepositoryAsync<RecurringTransactionPlan> repository)
: base(repository)
{
_repository = repository;
}
public IQueryable<RecurringTransactionPlan> RecurringTransactionPlanData()
{
return _repository.RecurringTransactionPlanData();
}
}
The repository:
public static class RecurringTransactionPlanRepository
{
public static IQueryable<RecurringTransactionPlan> RecurringTransactionPlanData(this IRepository<RecurringTransactionPlan> repository)
{
return repository.Queryable();
}
}
the above code all in separate projects, i am using this in MVC and also in console application, while using in MVC there is no error fetching data from db by UnityConfig.cs, but in console application we need to manually register and resolve the interfaces, i have tried this,
My Console Application:
public class RecurringTransaction
{
public readonly IRecurringTransactionPlanDataService _recurringTransactionPlanDataService;
public RecurringTransaction()
{
var container = new UnityContainer();
container.RegisterType<IRecurringTransactionPlanDataService, RecurringTransactionPlanDataService>();
_recurringTransactionPlanDataService = container.Resolve<IRecurringTransactionPlanDataService>();
}
}
public class Program
{
public static void Main(string[] args)
{
FeePaymentTracker.UnityConfig.RegisterComponents();
RecurringTransaction rt = new RecurringTransaction();
var restult = rt.GetRecurringTransactionRecords();
}
}
am getting the above error. expecting your ideas to resolve the error.
In your RecurringTransaction-method you create a new container and then you register RecurringTransactionPlanDataService in that new container. But you do not register the dependencies that the implementation RecurringTransactionPlanDataService has. That container will only have one registration.
var container = new UnityContainer();
container.RegisterType<IRecurringTransactionPlanDataService, RecurringTransactionPlanDataService>();
_recurringTransactionPlanDataService = container.Resolve<IRecurringTransactionPlanDataService>();
Since RecurringTransactionPlanDataService has a dependency to IRepositoryAsync<RecurringTransactionPlan> you need to register that as well.
Change your code to:
var container = new UnityContainer();
container.RegisterType<IRecurringTransactionPlanDataService, RecurringTransactionPlanDataService>();
container.RegisterType<IRepositoryAsync<RecurringTransactionPlan>, YourRepositoryImplementation>();
_recurringTransactionPlanDataService = container.Resolve<IRecurringTransactionPlanDataService>();
As a sidenote you may want to re-use the same container. In console-applications I usually resolve a "ProgramStarter", which then gets the correct injections. This way you only need to use the service locator anti-pattern in the root. But can use proper DI in the rest of the application.
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<ProgramStarter, ProgramStarter>();
// Pass the same container to the config.
FeePaymentTracker.UnityConfig.RegisterComponents(container);
var program = container.Resolve<ProgramStarter>();
program.Run();
}
}
public class ProgramStarter
{
IRecurringTransactionPlanDataService _dataService;
public ProgramStarter(IRecurringTransactionPlanDataService dataService)
{
_dataService = dataService;
}
public void Run()
{
// Do stuff.
}
}
in the code that you have posted you have an interface called IPaymentService and its implementation. It seems ok. But then in the screenshot you are trying to resolve a dependency called RecurringTransactionPlanDataService. Make your that you have registered this dependency. Could you add information about how you are registering the dependencies in the container?
The problem in your code is that you are trying to resolve the implementation instead of the interface. You should change the following line:
_recurringTransactionPlanDataService = container.Resolve<RecurringTransactionPlanDataService>();
with that:
_recurringTransactionPlanDataService = container.Resolve<IRecurringTransactionPlanDataService>();
Cheers,
I'm trying to utilize Ninject to help me build up a possible tree of service classes. I'd like to inject an ILogger instance using InCallScope so any child service class would use the same logger.
The logger implementation has a property called RootService, which would point to the upper-most service class instance which uses the logger. I would use information from it when categorizing logged events according to from which service class it has come from (child classes would not define another "log scope", hence I use InCallScope).
Can I fine-tune the ILogger Ninject binding so that I could have kind of a callback when the ILogger instance is activated, and I had there the instance too, into which it recently got injected? So there I could set the RootService property of my logger.
There's is the OnActivation binding extension which is a callback which is executed when ILogger is instanciated.
So you can do the following:
public class Test
{
[Fact]
public void Foo()
{
var kernel = new StandardKernel();
kernel.Bind<Service>().ToSelf();
kernel.Bind<Logger>().ToSelf()
.OnActivation((ctx, logger) =>
logger.Initalize(ctx.Request.Target.Member.DeclaringType));
var service = kernel.Get<Service>();
service.Logger.RootService.Should().Be(typeof(Service));
}
}
public class Logger
{
public Type RootService { get; private set; }
public void Initalize(Type rootService)
{
this.RootService = rootService;
}
}
public class Service
{
public Logger Logger { get; private set; }
public Service(Logger logger)
{
Logger = logger;
}
}
However, IContext does not provide access to the "parent" instance, so you can only access the type it's injected into, but not the instance.
Also, if that should be enough, there's no need to actually use the OnActivation extension, you should also be able to just do it like this:
public class Test
{
[Fact]
public void Foo()
{
var kernel = new StandardKernel();
kernel.Bind<Service>().ToSelf();
kernel.Bind<Logger>().ToSelf()
.WithConstructorArgument(
typeof(Type),
ctx => ctx.Request.Target.Member.DeclaringType);
var service = kernel.Get<Service>();
service.Logger.RootService.Should().Be(typeof(Service));
}
}
public class Logger
{
private readonly Type _rootService;
public Logger(Type rootService)
{
_rootService = rootService;
}
public Type RootService
{
get { return _rootService; }
}
}
public class Service
{
public Logger Logger { get; private set; }
public Service(Logger logger)
{
Logger = logger;
}
}
I have WinForm application and I want to use ServiceStack dependency injection mechanism:
public class AppHost : AppHostBase
{
public AppHost()
: base("MyName", typeof(AppHost).Assembly)
{
}
public override void Configure(Container container)
{
container.RegisterAutoWiredAs<AppApplicationContext, IAppApplicationContext>();
}
}
Then in some form class use it:
public class SomeClass : AppBaseForm
{
public IAppApplicationContext AppApplicationContext { get; set; }
public SomeClass(IAppApplicationContext appApplicationContext)
{
AppApplicationContext = appApplicationContext;
}
public SomeClass()
{
}
}
But AppApplicationContext is always null. When in parameterless constructor I write:
AppApplicationContext = AppHostBase.Resolve<IAppApplicationContext>();
then every thing is OK. But is this right way to do that? I mean AppApplicationContext should not be resolved by IoC automatically? And WinForm must have parameterless constructor.
Rest of code:
private static void Main()
{
var appHost = new AppHost();
appHost.Init();
}
public interface IAppApplicationContext
{
}
public class AppApplicationContext : IAppApplicationContext
{
}
You need to call AutoWire to have the container inject the dependancies. You can use it in your WinForm app like this:
public class SomeClass : AppBaseForm
{
public IAppApplicationContext AppApplicationContext { get; set; }
public SomeClass()
{
// Tell the container to inject dependancies
HostContext.Container.AutoWire(this);
}
}
When you use a regular ServiceStack service, the AutoWire happens behind the scenes during the request pipeline when ServiceStack creates an instances of your Service.
I have created a fully working example here. Note: The demo is just a console application, not WinForms but it does shows the IoC being used outside of the ServiceStack service, and it works no differently.
Can anyone help?
I have a wpf app (shouldn't matter) and in the Onstart i have my bootstrap stuff.. Its like this..
// Create unity container my service and repository
container = new UnityContainer()
.RegisterType<ISecurityRepository, SecurityRepository>()
.RegisterType<ISecurityService, SecurityService>();
Basically ISecurityService expects me to pass in a ISecurityRepository, hence the above fails.
But i am little confused, do i have to create a new IsecurityRespository and then pass it in, this defeats the object doesn't it?
Is there anyway i say "pass into SecurityService the ISecurityRepository from the container", but it hasn't been built yet?
Any ideas?
You don't have to create instances first. It all just works. That's the magic of IoC Containers.
Example:
public interface ISecurityService { }
public interface ISecurityRepository { }
public class SecurityService : ISecurityService
{
public SecurityService(ISecurityRepository repository)
{
Console.WriteLine("SecurityService created");
Console.WriteLine("Repository is " + repository);
}
public override string ToString()
{
return "A SecurityService";
}
}
public class SecurityRepository : ISecurityRepository
{
public SecurityRepository()
{
Console.WriteLine("SecurityRepository created");
}
public override string ToString()
{
return "A SecurityRepository";
}
}
public class MyClassThatNeedsSecurity
{
public MyClassThatNeedsSecurity(ISecurityService security)
{
Console.WriteLine("My class has security: " + security);
}
}
class Program
{
static void Main()
{
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType<ISecurityRepository, SecurityRepository>()
.RegisterType<ISecurityService, SecurityService>();
MyClassThatNeedsSecurity myClass =
container.Resolve<MyClassThatNeedsSecurity>();
}
}
}
This will print:
SecurityRepository created
SecurityService created
Repository is A SecurityRepository
My class has security: A SecurityService
You have a number of options, such as pre-creating your instances (as you showed in your follow-up post) or extending the lifetime of injected dependencies so that they're not recreated every time they're needed. But for the base case, this will work.
here is some more information. The constructor of my class is
public SecurityService(ISecurityRepository repository)
: base(repository)
{
}
After playing around a little bit, i managed to do the following but this causes me to create instances FIRST ... It seems to work.., but its an alternative.
// Create unity container my service and repository
ISecurityRepository securityRepository = new SecurityRepository();
ISecurityService securityService = new SecurityService(securityRepository);
container = new UnityContainer();
container.RegisterInstance<ISecurityRepository>(securityRepository);
container.RegisterInstance<ISecurityService>(securityService);