I'm now trying DI in ASP.NET Core.
I created a singleton object, and saved some application information to it.
I could inject Dependency into constructors, razor pages and repositories but don't know how to inject into entity.
MyConfig.cs:
public interface IMyConfig
{ ... }
public class MyConfig:IMyConfig
{
public MyConfig() {}
public string CompanyName { get { return _companyName; } }
public string ContactEMail { get { return _contactEmail; } }
}
program.cs:
builder.Services.AddSingleton<IMyConfig, MyConfig>(); // application information
builder.Services.AddSingleton<IMyRep, MyRep>(); // my repository
Repositories.cs:
public interface IMyRep
{
public string GetCompanyName();
public IEnumerable<IUser> GetUsers();
}
public class MyRep : IMyRep
{
private readonly DbContext _context;
private readonly MyConfig _config;
public MyRep(DbContext context, MyConfig config)
{
_context = context;
_config = config;
}
public string GetCompanyName() { return _config.CompanyName; }
public string GetContactEmail() { reutnr _config.ContactEmail; }
public GetUsers()
{
_context.Users.Select(m => m);
}
}
All above codes worked.
In addtion to above, I want to inject MyConfig to User entity.
It contains specific MyConfig information in User, like following.
user.cs:
public interface IUser
{
public int Id { get;set; }
public string Name { get;set; }
public string Company { get; }
}
public class User: IUser
{
private readonly IMyConfig _config;
public User(IMyConfig config)
{
_config = config;
}
public int Id { get;set; }
public string Name { get;set; }
public string Company { get { return _config.CompanyName; } }
}
Although I was tried to implement following code in program.cs, didn't work.
builder.Services.AddSingleton<IUser, User>();
Can I inject the object into the entity?