IAbpSession, ILogger, UserManager, How to inject these object in normal C# classes

521 views Asked by At

Is it possible to get instances of the below objects in normal C# classes:

IAbpSession, ILogger, UserManager, IConfigurationRoot

I want to use the object types in my custom classes which are not derived from other base classes. If not possible what base class should I derive my classes to have these object injected to my classes other than "MVC controllers", "Web API controllers" and "Application service"?

1

There are 1 answers

0
Alper Ebicoglu On BEST ANSWER

To use those interfaces in normal (your custom) C# classes you have to use dependency injection. First, you need to register your custom class in dependency injection system. It's very easy; Just inherit your custom class from ITransientDependency (or ISingletonDependency) and then inject IAbpSession or whatever class that's registered to dependency injection system. Let me show you a basic sample;

using Abp.Dependency;
using Abp.Runtime.Session;
using Castle.Core.Logging;
using Microsoft.Extensions.Configuration;
using MyCompanyName.AbpZeroTemplate.Authorization.Users;

public class MyCustomClass : ITransientDependency
{
    private readonly IAbpSession _abpSession;
    private readonly ILogger _logger;
    private readonly UserManager _userManager;
    private readonly IConfigurationRoot _configurationRoot;

    public MyCustomClass(IAbpSession abpSession, 
                         ILogger logger, 
                         UserManager userManager, 
                         IConfigurationRoot configurationRoot)
    {
        _abpSession = abpSession;
        _logger = logger;
        _userManager = userManager;
        _configurationRoot = configurationRoot;
    }

    public async void CreateUser()
    {
        await _userManager.CreateAsync(new User
        {
            Name = "Alper",
            TenantId = _abpSession.TenantId
        }, "1234567");


        var myConnectionString = _configurationRoot.GetConnectionString("Default");
        _logger.Debug("A new user is created using this connection string : " + myConnectionString);
    }
}

I tried to use all the interfaces that you mention.