Register abstract class with autofac - autofac

I just run this code in a quickly made console app with autofac assembly added:
builder.RegisterType<DbConnection>().As<IDbConnection>().WithParameter("connectionString", connectionString);
There was no exception although DbConnection is of abstract type.
Does autofac really create a concrete instance of DbConnection although its abstract?
How is that possible not to use:
builder.RegisterType().As().WithParameter("connectionString", connectionString);
Do I have to inherit from DbConnection and inject then MySqlConnection inherited from DbConnection?

You would only get the exception on resolution. You do need to register concrete types since you can't instantiate abstract types. So, as you said, you'd need a non-abstract type with a public constructor derived from DbConnection and register that as IDbConnection.

Related

Why JPA requires Entity classes to be non-final & fields non-final

Was reading about JPA here. Two of the requirements of an Entity class are that
The class must not be declared final. No methods or persistent instance variables must be declared final.
The class must have a public or protected, no-argument constructor.
Persistent instance variables must be declared private, protected, or package-private.
Was curious to know why are these conditions required ?
The class must not be declared final. No methods or persistent instance variables must be declared final.
JPA implementations use proxies in front of your entities to manage for example: Lazy loading. As a final class cannot be extended, a proxy cannot be built.
Some implementations as Hibernate can persist final classes but it can affect performance more info.
The class must have a public or protected, no-argument constructor.
These kind of frameworks and others in order to create new objects use ```Class.newInstance()`` that is the reason why a no arg constructor is needed.
Persistent instance variables must be declared private, protected, or package-private.
Being only accesible through accessor or business methods allow interception in proxies.
The reasons are (at least some of them):
JPA provider needs to create instances of the entity dynamically. If class would contain the only constructor which takes arbitrary arguments, JPA provider cannot figure out values for those arguments. That's why it must has a no-arg constructor.
JPA implementations deal with persisting instances of your entities classes. that's why the class, methods and variables cannot be final.
Because you don't want access to the variables from outside directly, in order to keep encapsulation - this is an OOP reason. another reason is that many frameworks of persistence are having a getter/setter method to identify POJO "properties".

Constructor and Unit Testing

I have a class XmlRecord. This class will deal with reading/writing to an xml file. At the moment, I have the following for that class:
class XmlRecord {
private val _file = new File("file.xml")
}
I want this class to somehow create the file if it doesn't exist. I know how to achieve this but I'm unsure how to design it in an Object Orientated way. I think I have two options:
Do I add a code to the constructor (or a call to a private method) that will create this file automatically if it doesn't exist. My problem with this method is that how do I unit test this as this code is effectively private code? Would I have to inject the File dependency so it could be mocked during testing?
Do I get the constructor to return an exception or implement a public method for the class so that the caller can use it to check if a file needs to be created? If so, the caller would then call another public method that would create the file. Again I think I would need to inject the dependency.
I hope that makes sense. I'm just trying to get a better grasp on designing my classes.
The presence of abstractions to accomplish DIP have other design
implications in an Object Oriented program:
All member variables in a class must be interfaces or abstracts.
All concrete class packages must connect only through interface/abstract classes packages.
No class should derive from a concrete class.
No method should override an implemented method.[5]
All variable instantiation requires the implementation of a Creational pattern as the Factory Method or the Factory pattern, or the more complex use of a Dependency Injection framework.
Dependency inversion principle

Interface Injection chapter in DI

I just start learning what is Dependency Injection and InversionOfControll is. But I cant get one thing. The interface injection is onle when I define some interface where describe method what need to be realized. And that method gets instance of some class as parameter, and then In class what implements interface just describe body of this method ?
An interface is only a contract that defines what public members a class should implement. It does not control the actual implementation - you need a concrete class to do that.
// This is only a contract that defines what members
// all concrete types must implement.
public interface ISomeType
{
void DoSomething();
}
// This class implements the interface. Therefore, it must
// have all of the methods the contract specifies. In some
// languages, this can be done implicitly just by adding the
// member, but it usually must be public.
public class SomeType : ISomeType
{
public void DoSomething()
{
Console.WriteLine("Hello World");
}
}
When you make a class implement an interface it implicitly means that instances of the class can be cast to the interface type.
ISomeType x = new SomeType();
Dependency Injection takes advantage of this behavior. You typically define both the interface type and the concrete implementation together in a mapping.
container.For<ISomeType>().Use<SomeType>();
Then when a service is declared to take ISomeType as a constructor argument, the map is used to determine which concrete type to create an instance of.
public class SomeService : ISomeService
{
private readonly ISomeType someType;
public SomeService(ISomeType someType)
{
if (someType == null) throw new ArgumentNullException("someType");
this.someType = someType;
}
}
The recommended way is to allow the DI container to do this implicitly when your entire object graph is composed (in the Composition Root), but it is possible also to do it explicitly (and it makes a better example):
ISomeService = container.GetInstance<ISomeService>();
Assuming that the container was configured to map ISomeService to SomeService (like I showed before with ISomeType), this one line of code will create an instance of SomeService and automatically inject an instance of SomeType into its constructor.
It is difficult to see the point in a simple example, though. Dependency Injection is meant for complex applications with many types. It simplifies things when the application is complex, but when the application is simple it has a tendency to make things more complex.

IoC DI, How to I resolve deep within the core?

Everyone says that an IOC should not be static or global in any way and should be created at root. But how do I get at it deep within my code?
Lets say I have an entry point ClassA. In here I can create an instance of an IOC and register all my interfaces to concrete types etc. But what then? Do I now start passing the IoC around ? Surely this would violate DIP ? None of the articles I have read discuss getting access to the Ioc and I would have thought it fundamental. I'm sure I must be missing something very simple here :)
Lets say ClassA creates a ClassB which creates A ClassC. Class C needs access to my resolved IDatabase. How does it get it ? Do I have to pass the IoC all the way in ?
You should be passing in the dependencies that a class needs. If Class C needs access to IDatabase then you must allow your IoC Container to pass an implementation of IDatabase into Class C, for example by having an IDatabase parameter on the Constructor for Class C.
If the IoC framework has the responsibility for creating Class C, then it also has the responsibility for giving Class C the dependencies it needs. As long as IDatabase has been registered in the IoC Container against a class which implements IDatabase, then an IDatabase parameter on Class C's constructor should be passed an implementation of IDatabase automatically.
To look at your example of ClassA creating ClassB which creates ClassC. Class A should not be 'newing' up an instance of ClassB using the 'new' keyword (I'm using C# or Java syntax here).
Rather, ClassA, ClassB and ClassC should all be registered with your IoC Container. If ClassA needs an instance of ClassB, then give ClassA a constructor which takes a parameter of ClassB. Your IoC Container should automatically resolve an instance of ClassB and pass it into ClassA. The same applies all the way down the chain as far as you need to go.
Using constructors (aka 'Constructor Injection') is not the only option here. You can often also use Property Injection, whereby public property setters are automatically set by your IoC Container (and there is also the much rarer 'Interface Injection'). But Constructor Injection is often the best way to go because it is then very clear exactly what dependencies a class needs before it can be instantiated; Property Injection can be unclear because a property may or may not be set by the IoC Container, depending on whether or not the property type has been registered or not.

Injecting with Gin into instance created by GWT.create

I have a custom deferred binder (rebind implementation) that instantiates objects. I would like to have some dependencies (#Inject annotated setter methods) within the instance returned by GWT.create() fulfilled by GIN. Is this possible?
So, given code such as:
Foo foo = GWT.create(Foo.class);
if foo's final implementation has:
#Inject
public void setBar(Bar bar) {
...
}
how do I get bar injected into the returned foo instance automatically by GIN?
Your Ginjector can have methods added to it for the purpose of injecting objects created in some other way. These must take one argument, and should specify the most specific type possible. For example, if MyViewImpl extends BaseView, and both types have dependencies to inject, but you declare
void injectBaseView(BaseView view);
in your ginjector, only the fields/setters declared on BaseView will be dealt with.
EDIT: Also, if no binding is declared, GWT.create will be used to create an instance, so you can have your cake and eat it to. One exception to that as far as I can recall, is when you want to GWT.create one type, but return another (see RPC interfaces for an example).