Hotchocolate: How can I inject dependency in request scope?

Created on 21 Jul 2018  路  10Comments  路  Source: ChilliCream/hotchocolate

Hello, thanks for great library!

I need to inject scoped dependency in my mutation. For example:

services.AddScoped<IUsersWriteService, UsersWriteService>();

...

public async Task<User> RegisterUserAsync(
    string name,
    string email,
    string password)
{
    var salt = PasswordUtility.GenerateSalt();
    var user = new User
    {
        Email = email,
        Name = name,
        Password = PasswordUtility.Encrypt(password, salt),
        Salt = salt
    };

    // inject usersWriteService
    return await usersWriteService.CreateUserAsync(user)
        .ConfigureAwait(false);
}

How can I do that?

bug

All 10 comments

Hi,

that is actually a bug in the current Version. I have fixed that in my local branch and think that the fix will roll out on Sunday evening. I will get back to you as soon a we have released the next Version.

This issue is now fixed in 0.4.0-preview-1.

@Dolfik1 you should probably wait for the final 0.4.0 since we are currently working on data loaders in the 0.4.0 which is a major change in the execution engine.

So, the previews could still have some issues. I think we will ship the final 0.4.0 at the end of this week.

@michaelstaib is I correctly inject dependencies?

Method 1:

public async Task<User>GetMe(IResolverContext resolverContext)
{
    var httpContext = resolverContext.Service<HttpContext>(); // returns null
    var service = resolverContext.Service<IUsersReadService>(); // throws exception
    // Cannot resolve scoped service 'Services.Read.IUsersReadService' from root provider.
    // ...
}

Method 2:

public async Task<User> GetMe(
    HttpContext httpContext,
    IUsersReadService service)
{
    // ...
}

If this is correct, DI still not working in 4.0 prerelease version. I am using 4.0.0-preview-2 version from nuget.

This should work in preview-2.

We have a test for this:

https://github.com/ChilliCream/hotchocolate/blob/next-version/src/AspNetCore.Tests/QueryMiddlewareTests.cs

HttpPost_WithHttpContext

Method 2 will work with the final release that is coming tomorrow:


public async Task<User> GetMe(
    [Service]HttpContext httpContext,
    IUsersReadService service)
{
    // ...
}

Method 1 should work with the current preview.

Although our integration test has the following under test:

https://github.com/ChilliCream/hotchocolate/blob/next-version/src/AspNetCore.Tests/Schema/Query.cs

I will write some more tests for this before releasing the final version 0.4.0 tomorrow.

I will look into this tomorrow morning.

This issue is done with release version 0.4.0. I have just tested it with your demo project.

Was this page helpful?
0 / 5 - 0 ratings