Support the ongoing development of Laravel.io →
posted 9 years ago
IOC

This is driving me bonkers because it seems I'm the only person with this problem.

I have a UserMessage Contract

namespace App\Contracts;

interface UserMessageContract
{
	public function send($user, $message);
}

Then I have the concrete class:

namespace App\Support\UserMessage;

class UserMessage implements UserMessageContract
{
    //some code here
}

Then the service provider:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\Support\UserMessage\UserMessage;
use App\Contracts\UserMessageContract;

class UserMessageProvider extends ServiceProvider
{
	protected $defer = true;

	public function register()
	{
        $this->app->singleton('usermessage', function ($app)
        {
            return new UserMessage();
        });

        $this->app->alias('usermessage', UserMessageContract::class);
	}

	public function provides()
	{
        return ['usermessage'];
	}
}

When I try to inject this into a controller, it gives me the "not instantiable" error.

I've tracked down the problem to the fact that the alias is not binding 'usermessage' to 'UserMessageContract::class'. For example, if I add 'usermessage' => UserMessageContract::class to the $alias array in Application.php, it works and the class gets resolved.

But currently it seems the error is thrown before the UserMessageProvider register function is even being called, so the alias is never registered. What am I doing wrong? I've read the documentation and looked at the source code to make sure I do it the way it's currently being done in source.

Is there another place I should register the alias?

Last updated 2 years ago.
0

Ok, so changing the service provider like so:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\Support\UserMessage\UserMessage;
use App\Contracts\UserMessageContract;

class UserMessageProvider extends ServiceProvider
{
    protected $defer = true;

    public function register()
    {
        $this->app->singleton(UserMessageContract::class, function ($app)
        {
            return new UserMessage();
        });

        $this->app->alias(UserMessageContract::class, 'usermessage');
    }

    public function provides()
    {
        return [UserMessageContract::class, 'usermessage'];
    }
}

gives the desired result. The class gets resolved out of the IoC container and I can still use the alias, i.e app('usermessage');

Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

john052 john052 Joined 26 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.