BITKit/Src/Core/ECS/Entity.cs

45 lines
1.4 KiB
C#
Raw Normal View History

2024-08-14 12:22:08 +08:00
using System;
2024-11-03 16:38:17 +08:00
using System.Collections.Generic;
2024-08-14 12:22:08 +08:00
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();
2025-03-09 13:38:23 +08:00
public CancellationToken CancellationToken { get; set; }
2024-08-14 12:22:08 +08:00
2024-11-08 21:06:30 +08:00
public IServiceProvider ServiceProvider => _serviceProvider ??= ServiceCollection.BuildServiceProvider();
private ServiceProvider _serviceProvider;
2025-03-09 13:38:23 +08:00
public IServiceCollection ServiceCollection
{
get
{
if (_serviceCollection is not null) return _serviceCollection;
_serviceCollection = new ServiceCollection();
_serviceCollection.AddSingleton<IEntity>(this);
return _serviceCollection;
}
}
private IServiceCollection _serviceCollection;
2024-11-08 21:06:30 +08:00
2024-08-14 12:22:08 +08:00
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()
{
2025-04-28 15:11:01 +08:00
_serviceProvider?.Dispose();
2024-08-14 12:22:08 +08:00
}
}
}