BITKit/Src/Core/ECS/Entity.cs

45 lines
1.4 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 int Id { get; set; } = Guid.NewGuid().GetHashCode();
public CancellationToken CancellationToken { get; set; }
public IServiceProvider ServiceProvider => _serviceProvider ??= ServiceCollection.BuildServiceProvider();
private ServiceProvider _serviceProvider;
public IServiceCollection ServiceCollection
{
get
{
if (_serviceCollection is not null) return _serviceCollection;
_serviceCollection = new ServiceCollection();
_serviceCollection.AddSingleton<IEntity>(this);
return _serviceCollection;
}
}
private IServiceCollection _serviceCollection;
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()
{
_serviceProvider.Dispose();
}
}
}