No implementation for List<? extends Vehicle> annotated with #Named(value="vehicles") was bound - kotlin

I want to inject a specific list of implementation classes to my Service class in a specific order via guice. I cannot use #ProvidesIntoSet because that will inject all implementations of my interface and I don't want that. I want to inject only some implementations and they should be in order. So, in my Module, I have this
#Provides
#Named(value = "vehicles")
fun getVehicles(
car: Car,
bus: Bus,
): List<Vehicle> {
return listOf(
car,
bus
)
}
Now, when I try to inject this list in my Service class like
class VehicleService #Inject constructor(
#Named("vehicles") private val vehicles: List<Vehicle>,
...
I get an error like
No implementation for List<? extends Vehicle> annotated with #Named(value="vehicles") was bound
How can I fix this issue?

You are running into this issue (https://github.com/google/guice/issues/1282.) with implied wildcard types.
You need to add #JvmSuppressWildcards as described in https://github.com/google/guice/issues/1641.

Related

Null controller when test with Mockito

I'm testing a controller that needs a Autowired Service.
I read in many place (example Mockito: How to test my Service with mocking?) I need to do it like this
#RunWith(JUnitPlatform.class)
public class AdminControllerTest {
#Mock
private AdminService service;
#InjectMocks
private AdminController adminController;
#Test
public void registerUser() {
Boolean resultReal = adminController.registerUser();
assertTrue(resultReal);
}
}
But it's fail and I see is because the adminController is null
Instead, if I create the controller like this
AdminController adminController = new AdminController();
It works, but then I can inject the mock.
Maybe I'm forgotten something
Per the documentation for InjectMocks:
MockitoAnnotations.openMocks(this) method has to be called to initialize annotated objects. In above example, openMocks() is called in #Before (JUnit4) method of test's base class. For JUnit3 openMocks() can go to setup() method of a base class. Instead you can also put openMocks() in your JUnit runner (#RunWith) or use the built-in MockitoJUnitRunner.
Thus, either:
call openMocks(this) somewhere before the test is run or
Use #RunWith(MockitoJUnitRunner.class) on the class

Why to pass values to the super class? subclass to super

I was checking Equatable package "how to use" examples and they pass values to the super class, and this subject like a blind spot for me, and I see it everywhere:
import 'package:equatable/equatable.dart';
class Person extends Equatable {
final String name;
// why? what's happening behind the scene here?
Person(this.name) : super([name]);
}
another example
#immutable
abstract class MyEvent extends Equatable {
MyEvent([List configs = const []]) : super(configs);
}
1- why we do that? why to pass values for abstract thing? for a blueprint? what's the use of this?
2- why sometimes developers pass values for abstract class like this?
3- what's happening behind the scene here?
4- what is the use cases for such a code?
thanks a lot.
A class being abstract doesn't exclude that it has some concrete members in Dart.
Take the following class as an example:
abstract class Foo {
Foo(this.value);
final int value;
#override
String toString() => value.toString();
}
While it is abstract, it has a concrete implementation of the property value, that is initialized via a custom constructor.
And since the parameter is required, the subclass must call the super constructor like so:
class Subclass extends Foo {
Subclass(): super(42);
}

Singleton subclass

I have an abstract base class and an implementation class like:
public abstract class Base
{
public Base getInstance( Class<? extends Base> clazz )
{
//expected to return a singleton instance of clazz's class
}
public abstract absMeth();
}
public A extends Base
{
//expected to be a singleton
}
In this example I can make A to be a singleton and even write getInstance in Base to return a singleton object of A for every call, doing this way:
public abstract class Base
{
public Base getInstance( Class<? extends Base> clazz )
{
try
{
return clazz.getDeclaredMethod("getInstance").invoke(null,null);
}
}
public abstract void absMeth();
}
public A extends Base
{
private static A inst;
private A(){}
public static A getInstance( )
{
if( inst!= null)
inst = new A();
return inst;
}
public void absMeth(){
//...
}
}
But my concern is how do I ensure that if somebody writes another class class B extends Base it should also be a singleton and it necessarily implements a static method called getInstance?
In other words I need to enforce this as a specification for all classes extending with the Base class.
You cannot trust classes that extend you to create a single instance of themselves1: even if you could somehow ensure that they all implement getInstance, there is no way to tell that inside that method they check inst before constructing a new instance of themselves.
Stay in control of the process: create a Map<Class,Base>, and instantiate the class passed in through reflection2. Now your code can decide whether to create an instance or not, without relying on the getInstance of a subclass.
1 A popular saying goes, "If you want a job done right, do it yourself."
2 Here is a link describing a solution based on setAccessible(true)
Singleton is a design pattern, not a language feature. It is pretty much impossible to somehow enforce it on the inheritance tree through syntax.
It certainly is possible to require all subclasses to implement a method by declaring it abstract but there is no way to control implementation details. Singleton is all about implementation details.
But why is this a concern at all? Do not make your app dependant on internal details of someone else's code. It is Bad Design™ and having this issue is a sure sign of it. Code against a well-defined interface and avoid relying on internal details.

Abstract Factory: are constructors with parameters allowed in concrete product classes?

In the abstract factory pattern, the concrete product created by a concrete factory implements a certain interface. Are there other constraints in the implementation of concrete products? For example, are not-default constructors allowed in concrete product classes?
Example:
public class XmlDaoFactory : DaoFactory
{
public override ICustomersDao CreateCustomersDao()
{
// XmlCustomersDao is a concrete product
return new XmlCustomersDao(1000, true);
}
...
}
For example, are not-default constructors allowed in concrete product classes?
Sure. That's the beauty of using an AbstractFactory; these details can be hidden in your concrete factory without the client having to be aware of them.

Using Ninject to bind an interface to multiple implementations unknown at compile time

I just recently started using Ninject (v2.2.0.0) in my ASP.NET MVC 3 application. So far I'm thrilled with it, but I ran into a situation I can't seem to figure out.
What I'd like to do is bind an interface to concrete implementations and have Ninject be able to inject the concrete implementation into a constructor using a factory (that will also be registered with Ninject). The problem is that I'd like my constructor to reference the concrete type, not the interface.
Here is an example:
public class SomeInterfaceFactory<T> where T: ISomeInterface, new()
{
public T CreateInstance()
{
// Activation and initialization logic here
}
}
public interface ISomeInterface
{
}
public class SomeImplementationA : ISomeInterface
{
public string PropertyA { get; set; }
}
public class SomeImplementationB : ISomeInterface
{
public string PropertyB { get; set; }
}
public class Foo
{
public Foo(SomeImplementationA implA)
{
Console.WriteLine(implA.PropertyA);
}
}
public class Bar
{
public Bar(SomeImplementationB implB)
{
Console.WriteLine(implB.PropertyB);
}
}
Elsewhere, I'd like to bind using just the interface:
kernel.Bind<Foo>().ToSelf();
kernel.Bind<Bar>().ToSelf();
kernel.Bind(typeof(SomeInterfaceFactory<>)).ToSelf();
kernel.Bind<ISomeInterface>().To ...something that will create and use the factory
Then, when requesting an instance of Foo from Ninject, it would see that one of the constructors parameters implements a bound interface, fetch the factory, and instantiate the correct concrete type (SomeImplementationA) and pass it to Foo's constructor.
The reason behind this is that I will have many implementations of ISomeInterface and I'd prefer to avoid having to bind each one individually. Some of these implementations may not be known at compile time.
I tried using:
kernel.Bind<ISomeInterface>().ToProvider<SomeProvider>();
The provider retrieves the factory based on the requested service type then calls its CreateInstance method, returning the concrete type:
public class SomeProvider : Provider<ISomeInterface>
{
protected override ISomeInterface CreateInstance(IContext context)
{
var factory = context.Kernel.Get(typeof(SomeInterfaceFactory<>)
.MakeGenericType(context.Request.Service));
var method = factory.GetType().GetMethod("CreateInstance");
return (ISomeInterface)method.Invoke();
}
}
However, my provider was never invoked.
I'm curious if Ninject can support this situation and, if so, how I might go about solving this problem.
I hope this is enough information to explain my situation. Please let me know if I should elaborate further.
Thank you!
It seems you have misunderstood how ninject works. In case you create Foo it sees that it requires a SomeImplementationA and will try to create an instance for it. So you need to define a binding for SomeImplementationA and not for ISomeInterface.
Also most likely your implementation breaks the Dependency Inversion Princple because you rely upon concrete instances instead of abstractions.
The solution to register all similar types at once (and the prefered way to configure IoC containers) is to use configuration by conventions. See the Ninject.Extensions.Conventions extenstion.