46 lines
1.6 KiB
C#
46 lines
1.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace BITKit.Entities
|
|
{
|
|
public class Entity : IEntity, IDisposable
|
|
{
|
|
public Entity()
|
|
{
|
|
ServiceCollection.AddSingleton<IEntity>(this);
|
|
}
|
|
public void WaitForInitializationComplete()
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
public int Id { get; set; } = Guid.NewGuid().GetHashCode();
|
|
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
|
|
private readonly CancellationTokenSource _cancellationTokenSource = new();
|
|
|
|
public IServiceProvider ServiceProvider => _serviceProvider ??= ServiceCollection.BuildServiceProvider();
|
|
private ServiceProvider _serviceProvider;
|
|
public IServiceCollection ServiceCollection { get; } = new ServiceCollection();
|
|
|
|
public object[] GetServices() => ServiceCollection.ToArray()
|
|
.Select(x => _serviceProvider.GetService(x.ServiceType)).ToArray();
|
|
public void Inject(object obj)
|
|
{
|
|
foreach (var fieldInfo in obj.GetType().GetFields(ReflectionHelper.Flags))
|
|
{
|
|
if (Attribute.IsDefined(fieldInfo, typeof(InjectAttribute)))
|
|
{
|
|
fieldInfo.SetValue(obj, ServiceProvider.GetService(fieldInfo.FieldType));
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_cancellationTokenSource.Cancel();
|
|
_serviceProvider.Dispose();
|
|
}
|
|
}
|
|
} |