The main attribute used to define new services and run them.
Each class flagged with a ServiceBindingAttribute will be automatically constructed on startup, and any services specified in the constructor will be injected as dependencies.
Examples
using NLog;
namespace NWN.Anvil.Samples
{
[ServiceBinding(typeof(ServiceA))]
public class ServiceA
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
public ServiceA()
{
Log.Info("Service A Loaded!");
}
}
[ServiceBinding(typeof(ServiceB))]
public class ServiceB
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
public ServiceB(ServiceA serviceA)
{
Log.Info($"Service B Loaded after {serviceA.GetType().Name}!");
}
}
}
using NLog;
namespace NWN.Anvil.Samples
{
[ServiceBinding(typeof(BasicScriptHandler))]
public class BasicScriptHandler
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
[ScriptHandler("test_nwscript")]
private void OnScriptCalled(CallInfo callInfo)
{
Log.Info($"test_nwscript called by {callInfo.ObjectSelf?.Name}");
}
}
}
using System.Linq;
using NLog;
namespace NWN.Anvil.Samples
{
[ServiceBinding(typeof(TriggerHandlerService))]
public class TriggerHandlerService
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
public TriggerHandlerService()
{
NwTrigger? trigger = NwObject.FindObjectsWithTag<NwTrigger>("mytrigger").FirstOrDefault();
if (trigger != null)
{
trigger.OnEnter += OnTriggerEnter;
}
}
private void OnTriggerEnter(TriggerEvents.OnEnter obj)
{
if (obj.EnteringObject.IsPlayerControlled(out NwPlayer? player))
{
Log.Info("Player entered trigger: " + player.PlayerName);
}
}
}
}
using System.Collections.Generic;
using System.Linq;
namespace NWN.Anvil.Samples
{
public interface IChatCommand
{
string Command { get; }
void ExecuteCommand(NwPlayer caller);
}
[ServiceBinding(typeof(IChatCommand))]
public class GpCommand : IChatCommand
{
public string Command => "!gp";
private const int Amount = 10000;
public void ExecuteCommand(NwPlayer caller)
{
caller.ControlledCreature?.GiveGold(Amount);
}
}
[ServiceBinding(typeof(IChatCommand))]
public class SaveCommand : IChatCommand
{
public string Command => "!save";
public void ExecuteCommand(NwPlayer caller)
{
caller.ExportCharacter();
caller.SendServerMessage("Character Saved");
}
}
[ServiceBinding(typeof(ChatHandler))]
public class ChatHandler
{
private readonly List<IChatCommand> chatCommands;
public ChatHandler(IEnumerable<IChatCommand> commands)
{
chatCommands = commands.ToList();
NwModule.Instance.OnPlayerChat += OnChatMessage;
}
public void OnChatMessage(ModuleEvents.OnPlayerChat eventInfo)
{
string message = eventInfo.Message;
foreach (IChatCommand command in chatCommands)
{
if (command.Command == message)
{
command.ExecuteCommand(eventInfo.Sender);
break;
}
}
}
}
}