Dependency Injection in Controllers - marcos8154/SocketAppServer GitHub Wiki
We can inject dependencies on the builders of our controllers. Let's imagine the following scenario: some (or all) controllers on our server create objects while performing actions. Imagine that creating these objects is complex, or perhaps costly. What if we could inject these ready objects into the controller builder?
First, let's define in the constructor the objects we want to receive as a parameter:
private SqlConnection DbConnection { get; }
public ExampleController(SqlConnection dbConnection)
{
DbConnection = dbConnection;
}
After that, create a class in your project, and implement the "IDependencyInjectorMaker" interface, located in the "MobileAppServer.ServerObjects" namespace.
public class DbConnectionInjectorMaker : IDependencyInjectorMaker
{
public string ControllerName { get { return "ExampleController"; } }
public object[] BuildInjectValues(RequestBody body)
{
string connectionString = "yourDatabaseConnectionString";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
return new object[]
{
conn
};
}
}
In the "ControllerName" property, return as a string the name of the controller to which the rule applies. If the rule applies to ALL controllers, return an empty string (string.Empty)
//injection for "ExampleController" only
public string ControllerName { get { return "ExampleController"; } }
//injection for ALL controllers in server
public string ControllerName { get { return string.Empty; } }
Within the "BuildInjectValues ()" method, you must build the objects and return an object [] as a result of the method.
ATTENTION: the order of the data in the array must strictly obey the order of the parameters in the constructor !!!
public object[] BuildInjectValues(RequestBody body)
{
string connectionString = "yourDatabaseConnectionString";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
return new object[]
{
conn
};
}
After the Dependency Injector has been properly deployed, you must register your instance on the server for it to work effectively:
server.RegisterDependencyInjectorMaker(new DbConnectionInjectorMaker());
Now the server knows that certain controllers need dependency injection, and it will request the objects for its newly created class to perform Controller injection.