How to handle different #Reference in OSGi DS Component - osgi

I'm having a problem with the following situation: The Server is waiting for one or more Functions. When a Function is bound the bindFunction is called. It needs to call doSomething() of any SpecificSystem.
When there is no SpecificSystem in my OSGi Container nothing happens which is good because the System Reference is not satisfied. The problem occurs when I add a SpecificSystem to my container. In that case the bindFunction is called before the System Reference is set leading to a NullPointerException inside bindFunction.
Is there any OSGi-way to make sure the System Reference is set when the bindFunction is executed so that I can safely call system.doSomething() inside the bindFunction?

You're treading in dangerous water here :-) You require ordering. Your code assumes the bindFunction reference is called after the system reference.
The OSGi specification guarantees that injection takes place in the lexical order of the reference name. (Of course, this is only true for the available services.)
The cheap way is to name your references so that the system reference's name is lexically lower than the name of the bindFunction reference, for example asystem or _system. The injection takes place in the lexical order.
This is ugly if course. A way to handle this is just inject the Function services and use them when needed instead of actively doing something in your bind function. This makes things more lazy which is almost always good.

In your example it looks like the System reference is mandatory. In this case your Server component will only come up if a System service is present.

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
#Component(name = "ServerComponent", immediate = false)
public class Server {
#Reference(cardinality = ReferenceCardinality.MANDATORY)
System system;
#Reference(cardinality = ReferenceCardinality.MANDATORY)
protected void bindFunction(Function func) {
}
#Activate
public void activate() {
}
}
You can call the doSomething() in activate method. Osgi guarantees method call order with #Reference annotation.
Provided that system and function references is acquired, The activate method will be called by OSGi environment. You can call the system.doSomething() method in the activate() method. #Reference(cardinality = ReferenceCardinality.MANDATORY) annotation means that call activate method after the references is acquired.

Related

Best approach for Dependency Injection in Laravel 5 package

I am developing a package for Laravel 5, and now I need to benefit from dependency injection to have a more scalable and relaible application, I don't know which approach is the best to take and why, this is a piece of my code and I need to injected the Lang class dependency
class MyController extends \App\Http\Controllers\Controller
{
public $text;
public $lang;
public function __construct()
{
// Some codes here
}
public function myFunction(){
$this->text = \Lang::get('package::all.text1');
}
}
In this link http://laravel.com/docs/4.2/ioc 2 approaches are suggested, Basic Usage and Automatic Resolution based on my understanding from the link
taking the first approach I need to add
App::bind('lang', function($app)
{
return new \Lang();
});
to the register part of application and then in the function I'll have something
like this :
public function myFunction()
{
$lang = \App::make('lang');
$this->text = $lang::get('package::all.text1');
}
The other way is to modify the constructor like
public function __construct(Lang $lang)
{
$this->lang = $lang;
}
And then instantiate object from Class like
$myController = App::make('MyController');
Which way is the better way to take for, considering that this class is a Controller and it will be called in the routes file, or please correct me if my understanding from the link is not right. please also inform me why you suggest any of those approaches.
It should be noted that using local IoC resolution ($app->make() stylee) is not much better than using the facades directly (Lang::get() stylee) - you're still very much relying on Laravel's specific classes without really making your code explicitly state that it needs these exact classes. So the general advice is to, as much as possible, code to an interface if you want your code to be as portable as possible.
Of course there are a couple of big downsides to this currently in PHP development:
These interfaces are not generally defined (except the PSR-3 LoggerInterface interface) so you still have to rely on a particular instance of the interface (in this case, Laravel's).
If you decide to make your own generic interface (or the FIG eventually creates some of these), the classes that Laravel provides for translation (for example) don't implement it anyway, so you then need to subclass the existing ones just to make it look like it implements your own interface. But hey, that's the current best practice, so I guess if you wanna be using the current best practices, code to an interface, and don't worry for the time being that the interface you're coding to is Laravel-specific.
But anyway, here are my thoughts on your specific question. First off I should say that I haven't actually used Laravel 5 yet (just the 4s), but I have generally followed its development.
If the class I am coding will use a given dependency quite a lot or as a core part of how the class works I will use constructor dependency injection. Examples here are the Request or some Repository class in a controller, or a business logic class in a console command class.
If what I need I only need for a specific purpose (maybe redirecting from a controller and needing to generate a URI) I will resolve a local version from the IoC container ($this->app->make()) and then use that. If I were using Laravel 5 and the method was called by Laravel directly (e.g. a controller's action method) I may use method injection for this, I'm not 100% sure.
As a final note, the general advice is that if your constructor method signatures get too big due to a lot of dependencies:
It's time to have a look at if your code relies too much on external dependencies. Maybe some of the functionality of your class can be extracted to its own class that splits the dependencies between the two.
You should consider using setter methods rather than constructor injection - so instead of accepting a Request object, you have a $class->setRequest() method. The downside of doing this is that you need to tell Laravel's IoC container how to instantiate your object (i.e. that these setters must be called). It's not that big a deal but something worth noting.
Relevant links:
Laravel 5's IoC article
Laravel 5's Controller injection advice

Mocking objects instantiated inside a class to be tested

So I am learning TDD using the many resources here on SO, but I just cant seem to figure out what I do with private/protected objects instantiated inside a given method/constructor. Lets say I have a connection string. That connection string is used to construct a Sqlcommand or Sqlhelper. Well I want to mock that Sqlhelper so that when I test other methods I don't have to rely on the results coming from my database. But I cant access the Sqlhelper.
How do I work around this?
Its generally best (except for a very few rare occasions) to test only the public interface of the class as a whole. Try not to use one of the workaround methods (such as private objects) unless you really have to. Accessing private members of classes in tests tends to look good at first as theres less code to write to test an object, however when things start to change (and they will) anything accessing the internals of a class makes it more difficult to change its implementation, this can be crippling to a project if most of the tests are written in this way.
In this particular case you are interacting with an external dependency outside of your control (i.e. SqlHelper), I'd recommend wrapping the SqlHelper object in your own object that implements an ISqlHelper interface (or a more reasonably named interface for your scenario).
e.g.
public interface ISqlHelperWrapper
{
void ExecuteQuery();
}
Then inject this in through the constructor of you're object under test:
public class SqlConsumer
{
private ISqlHelperWrapper _sqlHelper;
public SqlConsumer(ISqlHelperWrapper helper)
{
this._sqlHelper = helper;
}
public void QuerySomething()
{
this._sqlHelper.ExecuteQuery();
}
}
Not only is this a better design (you've isolated the sql implementation specific stuff from the SqlConsumer, and given it fewer reasons to change). But you can now mock the ISqlHelper instance using a mocking framework as well as switch the implementation on construction.
Given your connectionstring scenario above, you could initialise the sqlhelperwrapper (There are better names for this) with the connectionstring and your SqlConsumer object doesn't need to know about it.

Windows Service Implementing IDisposable - Is it bad practice?

I've come across this code:
public class ServiceLauncher2 : ServiceBase, IDisposable
And then this:
/// <summary>
/// Disposes the controllers
/// </summary>
// This is declared new as opposed to override because the base class has to be able to
// call its own Dispose(bool) method and not this one. We could just as easily name
// this method something different, but keeping it Dispose is just as valid.
public new void Dispose()
{
foreach (var mgr in _threadManagers)
mgr.Dispose();
base.Dispose();
}
I've never seen this in a Windows Service implementation before. Usually just OnStop/OnStart is overridden. Is this bad practice?
Let's count the ways this is bad practice:
The new keyword is grating, it tells the compiler to shut up about a potential problem in the code. A real one, the code that uses this class can easily end up calling ServiceBase.Dispose() instead. ServiceBase implements the disposable pattern, the correct way to do it is to override the protected Dispose(bool) method
The Dispose() method leaves a _threadManagers collection object behind that contains nothing but dead objects. Which makes the collection dead as a doornail as well, iterating it afterwards is meaningless. It should have been emptied
The only time this Dispose() method can be called is at service termination. Can't do it in OnStop(), it also disposed the ServiceBase. Disposing "controllers" a microsecond before the finalizers run and the process terminates makes no sense. Dispose() should only ever be used to allow unmanaged resources to be de-allocated early. There is no early when the process stops a millisecond later
This code makes no sense. Don't use it.
It does look non-standard but it is legit. So I wouldn't necessarily call it bad practice, though the fact that it introduces confusion makes it bad practice?
Does this run only as a service or is there console mode? (Console app would not get OnStop called.) Or is there some other (custom) way to stop this service process?
Ammending from my own earlier question of:
I'm not sure why new instead of override, especially since
base.Dispose() is being called.
Reason:
'SomeClass.Dispose()': cannot override inherited member
'System.ComponentModel.Component.Dispose()' because it is not marked
virtual, abstract, or override
In other words, the implementaion of ServiceBase.Dispose is not overridable.
Just to add to the already perfect answers by Hans and Paul: declaring ServiceLauncher2 as IDisposable is redundant, as ServiceBase is a Component which in turn is already IDisposable

Ninject: Choosing the wrong constructor

I have an ASP.NET MVC 3 application with Ninject v2.2.1.4. Everything was working great and then suddenly we started seeing Ninject attempting to create our DbContext using a constructor with a parameter over the parameterless constructor. Here are the bindings:
kernel.Bind<MyContext>().ToSelf().InRequestScope();
kernel.Bind<IUnitOfWork>().ToMethod(ctx => ctx.Kernel.Get<MyContext>());
kernel.Bind<DbContext>().ToMethod(ctx => ctx.Kernel.Get<MyContext>());
The MyContext is a DbContext object that implements the IUnitOfWork interface as well. I have set it up this way so the same context is injected into multiple repositories that are used in a single request. The MyContext constructors look like this:
public MyContext() { }
public MyContext(string connectionString) { }
public MyContext (long accountID) { }
public MyContext (Connection connection) { }
There are different constructors for different applications as they all use the same MyContext class. Looking at the bindings you would think when a MyContext class was requested that the parameterless constructor would be called but for whatever reason, it is not. The one with the long accountID parameter is called even though no accountID is being specified. This obviously throwns and exception statement that "No matching bindings are available, and the type is not self-bindable" It actually throws the exception when trying to generate a IUnitOfWork.
If I comment out the last three constructors everything works fine and the parameterless constructor is used. If I comment out any two of the parameterized constructors it tries to use the other and not the parameterless one.
The suggestions provided by Ninject are:
Suggestions:
1) Ensure that you have defined a binding for long.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.
We don't have anything for 1 as we don't want to. I'm not sure what 2 and 5 mean. I do not believe we have done 3 and we are not doing 4.
Any thoughts as to why it wouldn't use the parameterless constructor in this scenario.
#Xander's answer is right in general but Ninject has some very specific solutions in V3.
Ninject scores constructors by a specific algorithm which is to find the one with the most parameters it knows how to resolve as documented in this wiki article [which claims to be for V2.4, which was actually badged 3.0]. See the code. I think this is also on the wiki. If it's not, someone should put it there.
RE the change in behavior you've seen, the chances are either Implicit Self Binding is changing the goalposts (new registrations are being added during resolution) or you've added a Binding that has made one of the other constructors more attractive.
The [Inject] attribute trumps all other criteria which is what you're after (although you don't actually want to have container specific attributes in your code).
The WithConstructorArgument technique suggested is actually effected by using ToConstructor - doing a WCA will not influence the selection (and I reckon you won't get complaints about the redundant specifications.
The real bottom line is that you should never end up in as big a mess as this as alluded to in #Mark Seemann's comment on this related question.
Sadly, the above is all a lie. If you move off v2.2, this answer will become correct. If you can't or won't, you need to look at the equivalent source and tests to find out the rules from before that (from memory (and some google code that appeared in search results in my research), it was based on the constructor count, but not sure how equal scores are disambiguated.
Pretty sure that in 2.2, adding an [Inject] is the quick way out.
By default Ninject, along with other similar IoC frameworks, chooses the constructor with the most parameters. Specify which constructor to use during the initialization by the WithConstructorArgument extension method.
kernel.Bind<DbContext>()
.WithConstructorArgument("connectionString",
ConfigurationManager.ConnectionStrings["connection"]
.ConnectionString)
.ToMethod(ctx => ctx.Kernel.Get<MyContext>());
To force Ninject to use the default constructor place the [Inject] attribute on the constructor:
[Inject]
public MyContext() { }

Codeigniter: Use of load_class

I am writing my own logging class to save data in a DB. As I looked how CI is doing I noticed there is a log_message() function which handles the logging. There is a load_class function I can't assign to anything in the CI user guide.
1 Why do they put this into an extra function?
2 What/where loads this function files from?
Hope there are some CI guys how can answer :-)
Short answer:
You can write your own log class to override the default CI class:
<?php
// this file is /application/libraries/MY_Log.php
class MY_Log extends CI_Log {
public function write_log($level = 'error', $msg, $php_error = FALSE)
{
// Put your own logging function in here.
// If you want it to still log to a file as usual, use this:
parent::write_log($level, $msg, $php_error);
}
}
Long answer:
The load_class() function is basically a singleton loader. If the class has already been loaded, return a previous instance; otherwise, load it and create the singleton. It is very important in a framework like CI. You have to know that every time you call, say, a database function, it is applying it to the same object, not instantiating a new one (that would get really messy). All CI libraries function this way by default.
An important note: they changed how this functions significantly in version 2.0. Previously, it would only load from the /libraries folder, but now, it will load from /core or wherever you specify when calling the function.
Here's the process for loading, say, the Log class (from your example):
$_log =& load_class('Log');
$_log->write_log($level, $message, $php_error);
This runs the following checks, in sequence:
If the Log class already exists, we're done. Return the singleton.
If not, first check the /system/libraries folder for a "Log.php" file
If no file existed for step #2, now check /application/libraries for a "MY_Log.php" file (or whatever your subclass prefix is set to in your configuration)
If it loaded the default CI class (from the /system folder), but you DO have an extended class under /application, load that class too.
Return a new instance of the class (YOURS if it exists; otherwise, it's the CI_* class)
I've actually never needed to use the load_class() function, as it allows extension fairly seamlessly. However, it's good to know how it works.
So, to override a class, first find where the original resides (usually /system/libraries or /system/core). Put your extending file in the corresponding /application folder (this is important! If it's under /system/core, the extension MUST be under /application/core). Prefix both the filename and the class name with MY_ (or whatever you set in your configuration), and have it extend the CI_ base class.

Resources